employer cover photo
employer logo

VMware Interview Question

Height of the binary tree

Interview Answers

Anonymous

Jan 29, 2017

private static int Height(TreeNode root) { if (root == null) { return 0; } else { return Math.max(Height(root.left) + 1, Height(root.right) + 1); } }

4

Anonymous

Jun 8, 2016

log n

1

Anonymous

Jun 8, 2016

Or n log n

1

Anonymous

Dec 11, 2016

To find the height of a binary tree, you'd have to go over all the nodes. Because you don't know which path would be the longest. So this is O(n). The easiest solution would be doing it recursively, so the it'll be O(log n ) space, for the call stack. But is the tree is unbalansed you might get O(n) worst case. For example if the tree has only one very long branch with only one son to every node. { void* data; treeNode* left; treeNode* right; } int recursiveCalcHeight(treeNode* root) { if(!root) return 0; int leftHeight = recursiveCalcHeight(root->left); int reghtHeight = recursiveCalcHeight(root->right); int max_height = (leftHeight > rightHeight) ? leftHeight : rightHeight; return max_height+1; }

Anonymous

Aug 28, 2017

public int MaxDepth(TreeNode root) { if(root == null ) return 0; return Math.Max(MaxDepth(root.left),MaxDepth(root.right))+1; }