minimum element of binary tree - binary-tree

I have implemented functions to find the max and min element of the binary tree. But I am getting the wrong output for it.
Function to find the maximum of the binary tree.
int FindMax(struct TreeNode *bt)
{
//get the maximum value of the binary tree...
int max;
//get the maximum of the left sub-tree.
int left;
//get the maximum of the right sub-tree.
int right;
//get the root of the current node.
int root;
if(bt!=NULL)
{
root=bt->data;
//Call the left tree recursively....
left=FindMax(bt->leftChild);
//Call the right tree recursively...
right=FindMax(bt->rightChild);
if(left > right)
{
max=left;
}
else
{
max=right;
}
if(max < root)
{
max=root;
}
}
return max;
}
Function to find the min of binary tree.
int FindMin(struct TreeNode *bt)
{
//get the minimum value of the binary tree...
int min;
//get the minimum of the left sub-tree.
int left;
//get the minimum of the right sub-tree.
int right;
//get the root of the current node.
int root;
if(bt!=NULL)
{
root=bt->data;
//Call the left tree recursively....
left=FindMin(bt->leftChild);
//Call the right tree recursively...
right=FindMin(bt->rightChild);
if(left < right)
{
min=left;
}
else
{
min=right;
}
if(min > root)
{
min=root;
}
}
return min;
}
Output :
The maximum of tree 32767
The minimum of tree 0

private int minElem(Node node) {
int min= node.element;
if(node.left != null) {
min = Math.min(min, minElem(node.left));
}
if(node.right != null) {
min = Math.min(min, minElem(node.right));
}
return min;
}

Recursive implementation of finding minimum value in a generic binary tree:
Here is the BinaryTreeNode class:
package binaryTrees;
public class BinaryTreeNode {
private int data;
private BinaryTreeNode left;
private BinaryTreeNode right;
private int max;
private int min;
public int getMax() {
return BinaryTreeOps.maxValue(this);
}
public int getMin() {
return BinaryTreeOps.minValue(this);
}
public BinaryTreeNode(){
}
public BinaryTreeNode(int data){
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public BinaryTreeNode getLeft() {
return left;
}
public void setLeft(BinaryTreeNode left) {
this.left = left;
}
public BinaryTreeNode getRight() {
return right;
}
public void setRight(BinaryTreeNode right) {
this.right = right;
}
}
Here is the BinaryTreeOps class with the minValue operation: The crux is to use a static variable min so that we reset the same static variable every time we find a value lower than the previous value. It returns zero if pass a null node. You can modify this behaviour as per you requirement.
package binaryTrees;
public class BinaryTreeOps {
private static int min;
public static int minValue(BinaryTreeNode node){
min=node.getData(); //imp step, since min is static it is init by 0
minValueHelper(node);
return min;
}
public static void minValueHelper(BinaryTreeNode node){
if(node==null)
return;
if(node.getData()<min)
min=node.getData();
if(node.getLeft()!=null && node.getLeft().getData()<min)
min=node.getLeft().getData();
if(node.getRight()!=null && node.getRight().getData()<min)
min=node.getRight().getData();
minValueHelper(node.getLeft());
minValueHelper(node.getRight());
}
}

The problem is that you allow the function to be called on an empty tree. If bt is NULL then you are going to return an uninitialised value for min, which it seems just happens to be 0.
I don't like how you actually search the entire tree. FindMin should be O(logN) (if your tree is balanced), not O(N). I suggest you don't call blindly. Instead, always follow the path that is guaranteed to lead to a minimum. As soon as you find that value, your recursion stops:
int FindMin( struct TreeNode *bt )
{
if( !bt)
return 0; // Only if the tree contains nothing at all
if( bt->leftChild )
return FindMin(bt->leftChild);
return bt->data;
}
It's that easy.
Notice that I don't go down the right branch, because that will always be larger than the current node.

One way to do it (in C) using recursion:
In main:
printf("maximum (not BST) is: %d\n", FindMax(root, root->x));
The Function:
int FindMax(node *root, int max)
{
if(root->x > max) max = root->x;
if(root->left != NULL)
max = FindMax(root->left, max);
if(root->right != NULL )
max = FindMax(root->right, max);
return max;
}
Notice that here you have to pass the original root value when you first call the function, and then everytime pass the current maximum. You do not go into the function for empty nodes, and you don't create any new variables in the function itself.
The implementation of "ravi ranjan" only in c:
in main:
printf("minimum (not BST) %d\n", FindMin(root));
the function:
int FindMin(node *root)
{
int min = root->x;
int tmp;
if(root->left != NULL)
{
tmp = FindMin(root->left);
min = (min < tmp) ? min : tmp;
}
if(root->right != NULL)
{
tmp = FindMin(root->right);
min = (min < tmp) ? min : tmp;
}
return min;
}
Notice here you do create a local variable (much like the passed value in the previous example) and you also need to create a tmp variable for ease of use and readability. (or define a minimum macro beforehand).

Related

Valid Binary Tree

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
static class ReturnData {
public boolean isBST;
public int max;
public int min;
public ReturnData(boolean is, int mi, int ma) {
isBST = is;
min = mi;
max = ma;
}
}
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
ReturnData res = check(root);
if (res == null) {
return true;
}
return res.isBST;
}
private ReturnData check(TreeNode node) {
if (node == null) {
return null;
}
int min = node.val;
int max = node.val;
ReturnData left = check(node.left);
ReturnData right = check(node.right);
if (left != null) {
min = Math.min(min, left.min);
max = Math.max(max, left.max);
}
if (right != null) {
min = Math.min(min, right.min);
max = Math.max(max, right.max);
}
boolean isBST = true;
if (left != null && (!left.isBST || left.min >= node.val)) {
isBST = false;
}
if (right != null && (!right.isBST || right.min <= node.val)) {
isBST = false;
}
return new ReturnData(isBST, min, max);
}
}
I want to ask a LeetCode question, Question 98.
The question wants me to write an algorithm to check whether the given tree is a valid binary tree, so I wrote like this:
I create a constructor to initialize the return type, which contains the current node's value, max, and min value of its subtree.
I want to use recursion to check the validation.
But it doesn't work, I also check the solution but I still don't know why this way didn't work.
Hope someone could give me a hint, thanks.
The problem is in this condition:
left.min >= node.val
You'll want to see whether the maximum in the left tree exceeds the current node's value, so:
left.max >= node.val

SINGLE Recursive function for Print/Fetch kth smallest element in Binary search tree

I am trying to print the kth smallest element in an BST.
The first solution is using in-order traversal.
Next solution is finding the index of the current node by calculation the size of its left subtree.
Complete algo:
Find size of left subtree:
1.If size = k-1, return current node
2.If size>k return (size-k)th node in right subtree
3.If size<k return kth node in left subtree
This can be implemented using a separate count function which looks something like
public class Solution {
public int kthSmallest(TreeNode root, int k) {
//what happens if root == null
//what happens if k > total size of tree
return kthSmallestNode(root,k).val;
}
public static TreeNode kthSmallestNode(TreeNode root,int k){
if(root==null) return root;
int numberOfNodes = countNodes(root.left);
if(k == numberOfNodes ) return root;
if(k<numberOfNodes ) return kthSmallestNode(root.left,k);
else return kthSmallestNode(root.right,k-numberOfNodes );
}
private static int countNodes(TreeNode node){
if(node == null) return 0;
else return 1+countNodes(node.left)+countNodes(node.right);
}
}
But I see that we count the size for same trees multiple times, so one way is to maintain an array to store thes sizes like the DP way.
But I want to write a recursive solution for this.And here is the code I have written.
class Node {
int data;
Node left;
Node right;
public Node(int data, Node left, Node right) {
this.left = left;
this.data = data;
this.right = right;
}
}
public class KthInBST
{
public static Node createBST(int headData)
{
Node head = new Node(headData, null, null);
//System.out.println(head.data);
return head;
}
public static void insertIntoBst(Node head, int data)
{
Node newNode = new Node(data, null, null);
while(true) {
if (data > head.data) {
if (head.right == null) {
head.right = newNode;
break;
} else {
head = head.right;
}
} else {
if (head.left == null) {
head.left = newNode;
break;
} else {
head = head.left;
}
}
}
}
public static void main(String[] args)
{
Node head = createBST(5);
insertIntoBst(head, 7);
insertIntoBst(head, 6);
insertIntoBst(head, 2);
insertIntoBst(head, 1);
insertIntoBst(head, 21);
insertIntoBst(head, 11);
insertIntoBst(head, 14);
insertIntoBst(head, 3);
printKthElement(head, 3);
}
public static int printKthElement(Node head, int k)
{
if (head == null) {
return 0;
}
int leftIndex = printKthElement(head.left, k);
int index = leftIndex + 1;
if (index == k) {
System.out.println(head.data);
} else if (k > index) {
k = k - index;
printKthElement(head.right, k);
} else {
printKthElement(head.left, k);
}
return index;
}
}
This is printing the right answer but multiple times, I figured out why it is printing multiple times but not understanding how to avoid it.
And also If I want to return the node instead of just printing How do I do it?
Can anyone please help me with this?
Objective:
Recursively finding the kth smallest element in a binary search tree and returning the node corresponding to that element.
Observation:
The number of elements smaller than the current element is the size of the left subtree so instead of recursively calculating its size, we introduce a new member in class Node, that is, lsize which represents the size of the left subtree of current node.
Solution:
At each node we compare the size of left subtree with the current value of k:
if head.lsize + 1 == k: current node in our answer.
if head.lsize + 1 > k: elements in left subtree are more than k, that is, the k the smallest element lies in the left subtree. So, we go left.
if head.lsize + 1 < k: the current element alongwith all the elements in the left subtree are less than the kth element we need to find. So, we go to the right subtree but also reduce k by the amount of elements in left subtree + 1(current element). By subtracting this from k we make sure that we have already taken into account the number of elements which are smaller than k and are rooted as the left subtree of current node (including the current node itself).
Code:
class Node {
int data;
Node left;
Node right;
int lsize;
public Node(int data, Node left, Node right) {
this.left = left;
this.data = data;
this.right = right;
lsize = 0;
}
}
public static void insertIntoBst(Node head, int data) {
Node newNode = new Node(data, null, null);
while (true) {
if (data > head.data) {
if (head.right == null) {
head.right = newNode;
break;
} else {
head = head.right;
}
} else {
head.lsize++; //as we go left, size of left subtree rooted
//at current node will increase, hence the increment.
if (head.left == null) {
head.left = newNode;
break;
} else {
head = head.left;
}
}
}
}
public static Node printKthElement(Node head, int k) {
if (head == null) {
return null;
}
if (head.lsize + 1 == k) return head;
else if (head.lsize + 1 > k) return printKthElement(head.left, k);
return printKthElement(head.right, k - head.lsize - 1);
}
Changes:
A new member lsize has been introduced in class Node.
Slight modification in insertIntoBst.
Major changes in printKthElement.
Corner case:
Add a check to ensure that k is between 1 and the size of the tree otherwise a null node will be returned resulting in NullPointerException.
This is working on the test cases I have tried, so far. Any suggestions or corrections are most welcome.
:)

Size of the largest balanced binary subtree [duplicate]

This question already has answers here:
Balanced Binary Search Tree
(2 answers)
Closed 5 years ago.
I am trying to create a divide-and-conquer algorithm that, when run on the root of a binary tree, returns the size of the largest balanced binary subtree contained within the tree or in other words, the size of the largest subtree possible where the leaves are all at the same depth.
Some code might help. This is Java, but it's pretty generic.
static class Node
{
String val;
Node left, right;
}
static class MaxNode
{
Node node;
int depth;
}
static int depth(Node node)
{
if(node.left == null && node.right == null)
{
return 0;
}
else
{
return 1;
}
}
static int deepestSubtree(Node root, MaxNode maxNode)
{
if(root == null) return 0;
int depth = depth(root);
int leftDepth = deepestSubtree(root.left, maxNode);
int rightDepth = deepestSubtree(root.right, maxNode);
if(leftDepth == rightDepth)
{
depth += leftDepth;
}
if(depth > maxNode.depth)
{
maxNode.node = root;
maxNode.depth = depth;
}
return depth;
}
public static void main(String[] args)
{
Node root = buildTree();
MaxNode maxNode = new MaxNode();
deepestSubtree(root, maxNode);
if(maxNode.node == null)
{
System.out.println("No Balanced Tree");
}
else
{
int size = (int)Math.pow(2, maxNode.depth+1)-1;
System.out.format("Node: %s, Depth: %d, Size: %d\n", maxNode.node.val, maxNode.depth, size);
}
}
For your example tree the output is:
Node: D, Depth: 2, Size: 7

Check if a binary tree is balanced with iterative function?

I need to implement a non-recursive function to determine if a binary tree is balanced or not.
Anyone?
Thanks!!!
Assuming that by "balanced", you mean "height-balanced" in the AVL-tree sense, and you can store arbitrary information for each node,
For each node in post-order,
if either child doesn't exist, assume its respective height is 0.
if the height of both children differs by more than one, the tree is not balanced.
otherwise, this node's height is the larger of both children's heights.
If this point is reached, the tree is balanced.
One way to perform post-order traversal:
start at the root
loop
if this node's left child exists and does not have its height computed, visit its left child next.
else if this node's right child exists and does not have its height computed, visit its right child next.
else
compute this node's height, possibly returning early
if this node is not the root, visit its parent next.
If this point is reached, the tree is balanced.
Try this,
public class BalancedBinaryTree {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public boolean isBalanced(TreeNode root) {
if (root==null) {
return true;
}
Stack<TreeNode> stack = new Stack<>();
Map<TreeNode, Integer> map = new HashMap<>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
if ((node.left==null || (node.left!=null && map.containsKey(node.left))) && (node.right==null || (node.right!=null && map.containsKey(node.right)))) {
int right = (node.right==null) ? 0 : map.get(node.right);
int left = (node.left==null) ? 0 : map.get(node.left);
if (Math.abs(right-left)>1) {
return false;
} else {
map.put(node, Math.max(right, left)+1);
}
} else {
if (node.left!=null && !map.containsKey(node.left)) {
stack.push(node);
stack.push(node.left);
} else {
stack.push(node);
stack.push(node.right);
}
}
}
return true;
}
public static void main(String[] args) {
BalancedBinaryTree b = new BalancedBinaryTree();
boolean v = b.isBalanced(new TreeNode(3, new TreeNode(9), new TreeNode(20, new TreeNode(15), new TreeNode(7))));
System.out.println(v);
v = b.isBalanced(new TreeNode(1, new TreeNode(2, new TreeNode(3, new TreeNode(4), new TreeNode(4)), new TreeNode(3)), new TreeNode(2)));
System.out.println(v);
v = b.isBalanced(new TreeNode(1, new TreeNode(2, new TreeNode(4, new TreeNode(8), null), new TreeNode(5)), new TreeNode(3, new TreeNode(6), null)));
System.out.println(v);
}
}
Here is a c++ code that works, inspired by the postorder traversal. The code is not commented because i do not think a simple comment is enough to explain the whole algorithm. You can execute this code manually with the example below and then you will understand everything.
bool IsBalance(const Node *head)
{
std::stack<const Node *> s;
std::stack<int> sV;
const Node *curr = head, *lastVisit = nullptr;
int deep = 0;
while (curr || !s.empty())
{
while (curr)
{
s.push(curr);
sV.push(-1);
curr = curr->m_pLeft;
}
curr = s.top();
if (sV.top() == -1)
{
sV.top() = deep;
}
if (!curr->m_pRight || curr->m_pRight == lastVisit)
{
if (!curr->m_pRight)
{
deep = 0;
}
if (std::abs(sV.top() - deep) > 1)
{
return false;
}
deep = std::max(sV.top(), deep) + 1;
lastVisit = curr;
s.pop();
sV.pop();
curr = nullptr;
}
else
{
deep = 0;
curr = curr->m_pRight;
}
}
return true;
}
examples:
(1) 21,10,3,1,#,#,5,#,6,#,#,15,12,#,#,18,16,#,#,20,#,#,35,30,22,#,#,#,40,36,#,#,42,#,45,#,#
(2) 1,2,#,4,#,5,#,#,3,6,8,#,#,#,7,#,#
(3) 3,1,#,2,#,#,#
Where nodes are arranged by PreOrder, separated by commas, and # indicates an empty node.
Find the height of left subtree and right subtree for a node of the tree, using Level order traversal and check if that node is balanced.
Repeat this for every node of the tree. For traversing all the nodes we can use level order traversal to avoid recursion.
int height(TreeNode* root){
if(!root){
return 0;
}
queue<TreeNode*> q;
q.push(root);
int count=0;
while(!q.empty()){
int size=q.size();
for(int i=0;i<size;++i){
TreeNode* temp=q.front();
q.pop();
if(temp->left){
q.push(temp->left);
}
if(temp->right){
q.push(temp->right);
}
}
count++;
}
return count;
}
bool checkEveryNode(TreeNode* root){
if(!root){
return true;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int count=q.size();
for(int i=0;i<count;++i){
TreeNode* temp=q.front();
q.pop();
int left=height(temp->left);
int right=height(temp->right);
if(abs(left-right)>1){
return false;
}
if(temp->left){
q.push(temp->left);
}
if(temp->right){
q.push(temp->right);
}
}
}
return true;
}
bool isBalanced(TreeNode* root) {
return checkEveryNode(root);
}
Time complexity of this approach is O(n^2), as we need to traverse all the descendant nodes for finding the height of a node(N) and we need to do this for all the nodes(N)

Traversing the Binary Search Tree

I was reading through Introduction to algorithms i came across this problem about In-order Traversal of binary search tree without using a stack or recursion. Hint says to assume that testing of pointers for equality is a legitimate operation.I'm stuck finding the solution to this problem. Please give me some direction. I'm not looking for the code. Just give me the right direction.
Exact duplicate here
No stack nor recursion means you have to use pointers. Not giving you code nor the exact answer, since you asked not to :)
Think about how to explore the tree without using recursion: what would you need to do? What pointer(s) do you need to keep? Can a tree node have a pointer to the parent?
Hope it helps.
We need a Threaded Binary Tree to do in-order Traversal without recursion / stack.
Wiki says 'A binary tree is threaded by making all right child pointers that would normally be null point to the inorder successor of the node, and all left child pointers that would normally be null point to the inorder predecessor of the node'
So you are given a normal Binary Tree , Convert it into a Threaded Binary Tree which can be done using Morris Traversal.
What you are going to do in Morris Traversal is to connect each node with its in-order successor. So while visiting a node ,Search for its in-order predecessor and let it be Pred.
then make Pred->right=Current node and we have to revert back the changes too. You can better refer this http://www.geeksforgeeks.org/archives/6358 for a great explanation.
Hello Parminder i have implemented your question in java.Please check it once
class InorderWithoutRecursion {
public static void morrisTraversal(TreeNode root) {
TreeNode current,pre;
if(root == null)
return;
current = root;
while(current != null){
if(current.left == null){
System.out.println(current.data);
current = current.right;
}
else {
/* Find the inorder predecessor of current */
pre = current.left;
while(pre.right != null && pre.right != current)
pre = pre.right;
/* Make current as right child of its inorder predecessor */
if(pre.right == null){
pre.right = current;
current = current.left;
}
/* Revert the changes made in if part to restore the original
tree i.e., fix the right child of predecssor */
else {
pre.right = null;
System.out.println(current.data);
current = current.right;
}
}
}
}
public static void main(String[] args) {
int[] nodes_flattened = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
TreeNode root = TreeNode.createMinimalBST(nodes_flattened);
morrisTraversal(root);
}
}
For TreeNode class below code will help you..
public class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode parent;
public TreeNode(int d) {
data = d;
}
public void setLeftChild(TreeNode left) {
this.left = left;
if (left != null) {
left.parent = this;
}
}
public void setRightChild(TreeNode right) {
this.right = right;
if (right != null) {
right.parent = this;
}
}
public void insertInOrder(int d) {
if (d <= data) {
if (left == null) {
setLeftChild(new TreeNode(d));
} else {
left.insertInOrder(d);
}
} else {
if (right == null) {
setRightChild(new TreeNode(d));
} else {
right.insertInOrder(d);
}
}
}
public boolean isBST() {
if (left != null) {
if (data < left.data || !left.isBST()) {
return false;
}
}
if (right != null) {
if (data >= right.data || !right.isBST()) {
return false;
}
}
return true;
}
public int height() {
int leftHeight = left != null ? left.height() : 0;
int rightHeight = right != null ? right.height() : 0;
return 1 + Math.max(leftHeight, rightHeight);
}
public TreeNode find(int d) {
if (d == data) {
return this;
} else if (d <= data) {
return left != null ? left.find(d) : null;
} else if (d > data) {
return right != null ? right.find(d) : null;
}
return null;
}
private static TreeNode createMinimalBST(int arr[], int start, int end){
if (end < start) {
return null;
}
int mid = (start + end) / 2;
TreeNode n = new TreeNode(arr[mid]);
n.setLeftChild(createMinimalBST(arr, start, mid - 1));
n.setRightChild(createMinimalBST(arr, mid + 1, end));
return n;
}
public static TreeNode createMinimalBST(int array[]) {
return createMinimalBST(array, 0, array.length - 1);
}
}

Resources