Tree: Height of a Binary Tree

Sort by

recency

|

962 Discussions

|

  • + 0 comments

    C++ solution:

    -1 in the base case accounts for the fact that path length = nodes - 1;

        int height(Node* root) {
            if (root == NULL) {return -1;}
            
            int left = 1 + height(root->left);
            int right = 1 + height(root->right);
            
            if (left > right) {return left;}
            else {return right;}
    			
        }
    
  • + 0 comments

    Calculates the height of a binary tree recursively. ` public static int recHeight(Node node, int counter) { // Base Case: If the node is null, return the current counter as the height if (node == null) { return counter; }

    // Recursive Case: Calculate the height of the left and right subtrees
    int leftHeight = recHeight(node.left, counter + 1);
    int rightHeight = recHeight(node.right, counter + 1);
    
    // Return the greater of the two heights
    return Math.max(leftHeight, rightHeight);
    

    } `

  • + 0 comments

    Swift version seems to be broken and crashes for any tree with more than one node due to an error in reading the input here:

    let t = Int(readLine()!)!

    for _ in 0..

    root = tree.insert(root: root, data: Int(readLine()!)!)
    

    }

    The problem is that the 'for' loop expects for each node data to appear on a separate line, while they all on the same line separated by commas.

  • + 0 comments
    Python:
    
    `def height(root):
    	if root.left == None and root.right== None:
    		return 0
    	elif root.left == None:
    		return 1+ height(root.right)
    	elif root.right == None:
    		return 1+ height(root.left)
    	else:
    		return 1 + max(height(root.left),height(root.right))`
    
  • + 0 comments
    def height(curr_node, level=-1):
        if curr_node is None:
            return level
            
        return max(height(curr_node.left, level + 1), height(curr_node.right, level + 1))
    

    `