Tree: Height of a Binary Tree

Sort by

recency

|

12 Discussions

|

  • + 0 comments

    How was this problem classified as requiring advanced problem solving? It is much easier than many supposedly easy problems in this preparation kit.

  • + 0 comments

    Java 8, O(log n)

    public static int height(Node root) {
                if (root == null) {
                    return -1;
                } else {
                    return 1 + Math.max(height(root.left), height(root.right));
                }
            }
    
  • + 0 comments

    It seems it's broken on JS: it's comparing NaN with root.data preparing the Tree. and all the nodes are on the right then...

  • + 1 comment

    C++ using a stack and iteration instead of recursion.

        int height(Node* root) {
            struct Frame {
                Node* node{};
                int height = 0;
            };
            std::stack<Frame> stack;
            stack.push({root});
            int max = INT_MIN;
            while (!stack.empty()) {
                const auto top = stack.top();
                stack.pop();
                max = std::max(max, top.height);
                if (top.node->right)
                    stack.push({top.node->right, top.height + 1});
                if (top.node->left)
                    stack.push({top.node->left, top.height + 1});
            }
            return max;
        }
    
  • + 0 comments
    def height(root):
        '''
        Solved with BFS, this is adapt to get shortest distances in tree with edges weight=1
        '''
        explored = {}
        explored[root.info] = 0
        q = deque()
        q.append(root)
        height_tree = 0
        while q:
            v = q.popleft()
            children = []
            if v.left:
                children.append(v.left)
            if v.right:
                children.append(v.right)
            for w in children:
                if not explored.get(w.info) and (w.info not in explored):
                    explored[w.info] = explored[v.info] + 1
                    height_tree = max(explored[w.info], height_tree)
                    q.append(w)
        return height_tree