Consider the following binary tree structure and code to calculate its height. What is the printed height?
package main import "fmt" type Node struct { Val int Left *Node Right *Node } func height(root *Node) int { if root == nil { return 0 } leftHeight := height(root.Left) rightHeight := height(root.Right) if leftHeight > rightHeight { return leftHeight + 1 } return rightHeight + 1 } func main() { root := &Node{Val: 1} root.Left = &Node{Val: 2} root.Right = &Node{Val: 3} root.Left.Left = &Node{Val: 4} root.Left.Right = &Node{Val: 5} fmt.Println(height(root)) }
Height is the number of nodes on the longest path from root to a leaf.
The longest path is from root (1) to node 4 or 5, which has 3 nodes, so height is 3.
What is the output of the height function for this skewed binary tree?
package main import "fmt" type Node struct { Val int Left *Node Right *Node } func height(root *Node) int { if root == nil { return 0 } leftHeight := height(root.Left) rightHeight := height(root.Right) if leftHeight > rightHeight { return leftHeight + 1 } return rightHeight + 1 } func main() { root := &Node{Val: 1} root.Right = &Node{Val: 2} root.Right.Right = &Node{Val: 3} root.Right.Right.Right = &Node{Val: 4} fmt.Println(height(root)) }
Height counts nodes along the longest path from root to leaf.
The tree is skewed to the right with 4 nodes in a line, so height is 4.
In the height function for a binary tree, what is the returned height when the input root node is nil?
Think about the base case for recursion when there is no node.
The height of an empty tree is defined as 0 because there are no nodes.
Consider this height function code. It returns wrong height for some trees. What is the bug?
func height(root *Node) int { if root == nil { return -1 } leftHeight := height(root.Left) rightHeight := height(root.Right) if leftHeight > rightHeight { return leftHeight } return rightHeight }
Check base case and how height is calculated from children.
The function returns -1 for nil nodes but does not add 1 for current node, so height is off by one. Both issues cause wrong output.
Which code snippet correctly calculates the height of a binary tree using an iterative method (level order traversal)?
Height is number of levels. Use queue to process nodes level by level.
Option A correctly uses a queue to process each level and increments height after processing all nodes at that level.