I know this is pretty straight forward code but wondering how exactly the internal working is.
public static int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
System.out.print(getHeight(root.left) +"\t");
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
For my understanding, I added print statement but it results the following.
printing root.left() prints this: 0 0 0 1 0 0 0
printing root.right() prints this: 0 0 2 0 0 3 0 0 2 0 0 0 1 0
Following is the Tree created in the main program:
TreeNode parent = new TreeNode(10);
parent.insertInOrder(2);
parent.insertInOrder(13);
parent.insertInOrder(5);
parent.insertInOrder(6);
parent.insertInOrder(15);
parent.insertInOrder(6);
How is this printing the above result and how is it working. If anyone can explain me with the above example, it would really help me.
I know how traversals work and how to print the tree but I really want to understand the above output. If anyone can help then it would be great.
void setLeftChild(TreeNode left)
{
this.left = left;
if(left == null)
{
left.parent = this;
}
}
void setRightChild(TreeNode right)
{
this.right = right;
if(right == null)
{
right.parent = this;
}
}
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);
}
}
size++;
}
insertInOrderwork? - arunmoezhisizea global variable? And are you doing any balancing here or is it an unbalanced bst? As a side note, do insertion using an iterative code. Try to avoid recursion if you can. They are slow. - arunmoezhi