employer cover photo
employer logo

Domanda di colloquio di VMware

Height of the binary tree

Risposte di colloquio

Anonimo

29 gen 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

Anonimo

8 giu 2016

log n

1

Anonimo

8 giu 2016

Or n log n

1

Anonimo

11 dic 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; }

Anonimo

28 ago 2017

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