Tree: Height of a Binary Tree

Sort by

recency

|

13 Discussions

|

  • + 0 comments

    confirmed broken in JS.

  • + 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

      C++, recursion.

          int height(Node* root) {
              if (!root || (!root->left && !root->right))
                  return 0;
              return 1 + std::max(
                  height(root->left),
                  height(root->right)
              );
          }