Sort by

recency

|

489 Discussions

|

  • + 0 comments

    Javascript code:

    // Start of function getHeight
    this.getHeight = function(root) {
    
        if (root===null) return -1;
        leftheight=this.getHeight(root.left);
        rightheight=this.getHeight(root.right);
        return Math.max(leftheight,rightheight)+1;
    
    }; // End of function getHeight
    

    Don't understand how the output get 2 with the below input. Any expert can help to shed some light please. Thanks!

    9 20 50 35 44 9 15 62 11 13

  • + 0 comments

    Python 3 solution

    python def getHeight(self,root):

        if root.left:
            left = self.getHeight(root.left) + 1
        else:
            left = 0
        if root.right:
            right =self.getHeight(root.right) +1
        else:
            right = 0
    
        return max(left, right)
    
  • + 0 comments
    c# csharp
    
    solution that doesn't use recursion
    
    private static int getHeight(Node root)
    {
        if (root == null)
        {
            return -1; // height of empty tree is -1
        }
    
        Queue<Node> queue = new Queue<Node>();
        queue.Enqueue(root);
        int height = -1;
    
        while (queue.Count > 0)
        {
            int nodeCount = queue.Count;  // Number of nodes at the current level
            height++;
    
            // Process each node at the current level
            while (nodeCount > 0)
            {
                Node node = queue.Dequeue();
    
                // Enqueue left and right children of the current node
                if (node.left != null)
                {
                    queue.Enqueue(node.left);
                }
                if (node.right != null)
                {
                    queue.Enqueue(node.right);
                }
    
                nodeCount--;
            }
        }
    
        return height;
    }
    
  • + 0 comments

    This is what I came up with:

        def getHeight(self,root):
            if root is None:
                return -1
            else:
                return max(self.getHeight(root.left),self.getHeight(root.right)) + 1
    
  • + 0 comments

    Using Python 3’s pattern-matching:

    def getHeight(self, root):
        match root:
            case Node(left=None, right=None):
                return 0
            case Node(left=None):
                return 1 + self.getHeight(root.right)
            case Node(right=None):
                return 1 + self.getHeight(root.left)
            case _:
                return max(1 + self.getHeight(root.left), 1 + self.getHeight(root.right))