Tree: Height of a Binary Tree

Sort by

recency

|

964 Discussions

|

  • + 1 comment

    Feedback: as i am writing right now, the JavaScript (Node.js) environment is broken. We need to switch to another working language environment (like python3).

    Error:

    node:internal/streams/writable:474
    
          throw new ERR_INVALID_ARG_TYPE(
    
          ^
    
    TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
    
  • + 0 comments

    Haskell

    module Main where
    
    data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show)
    
    inOrder :: Tree a -> [a]
    inOrder Empty = []
    inOrder (Node a left right) = inOrder left ++ [a] ++ inOrder right
    
    insertNode :: (Ord a) => Tree a -> a -> Tree a
    insertNode Empty x = Node x Empty Empty
    insertNode (Node a left right) x
        | x < a = Node a (insertNode left x) right
        | x > a = Node a left (insertNode right x)
        | otherwise = Node a left right
    
    height :: Tree a -> Int
    height Empty = 0
    height (Node _ Empty Empty) = 0
    height (Node _ left right) = 1 + max (height left) (height right)
    
    main :: IO ()
    main = do
        _ <- getLine
        xs <- fmap (map read . words) getLine :: IO [Int]
        let tree = foldl insertNode Empty xs
        print $ height tree
    
  • + 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.