Given the binary tree below, what is the inorder traversal output?
Tree structure:
2 / \ 1 3
package main import "fmt" type Node struct { Val int Left *Node Right *Node } func inorder(root *Node) { if root == nil { return } inorder(root.Left) fmt.Print(root.Val, " ") inorder(root.Right) } func main() { root := &Node{Val: 2} root.Left = &Node{Val: 1} root.Right = &Node{Val: 3} inorder(root) }
Inorder traversal visits left child, then root, then right child.
Inorder traversal visits nodes in the order: left subtree, root, right subtree. For this tree, it visits 1, then 2, then 3.
Consider the binary tree:
4
/ \
2 5
/ \
1 3What is the output of inorder traversal?
package main import "fmt" type Node struct { Val int Left *Node Right *Node } func inorder(root *Node) { if root == nil { return } inorder(root.Left) fmt.Print(root.Val, " ") inorder(root.Right) } func main() { root := &Node{Val: 4} root.Left = &Node{Val: 2} root.Right = &Node{Val: 5} root.Left.Left = &Node{Val: 1} root.Left.Right = &Node{Val: 3} inorder(root) }
Remember inorder is left, root, right recursively.
Inorder traversal visits nodes in ascending order for this BST: 1, 2, 3, 4, 5.
Analyze the following Go code for inorder traversal. What error will it produce when run?
package main import "fmt" type Node struct { Val int Left *Node Right *Node } func inorder(root *Node) { if root == nil { return } inorder(root.Left) fmt.Print(root.Val) inorder(root.Right) } func main() { var root *Node inorder(root.Left) }
Check what happens when you access a field of a nil pointer.
root is nil, so root.Left causes a runtime panic due to nil pointer dereference.
Given the binary tree:
10
/ \
5 15
/ / \
3 12 20How many nodes will inorder traversal visit?
Count all nodes in the tree.
There are 6 nodes: 10, 5, 15, 3, 12, 20. Inorder traversal visits all 6 nodes.
Given the BST:
5
/ \
3 8
/ / \
2 6 9After inserting 7, what is the inorder traversal output?
package main import "fmt" type Node struct { Val int Left *Node Right *Node } func insert(root *Node, val int) *Node { if root == nil { return &Node{Val: val} } if val < root.Val { root.Left = insert(root.Left, val) } else { root.Right = insert(root.Right, val) } return root } func inorder(root *Node) { if root == nil { return } inorder(root.Left) fmt.Print(root.Val, " ") inorder(root.Right) } func main() { root := &Node{Val: 5} root.Left = &Node{Val: 3} root.Right = &Node{Val: 8} root.Left.Left = &Node{Val: 2} root.Right.Left = &Node{Val: 6} root.Right.Right = &Node{Val: 9} root = insert(root, 7) inorder(root) }
Inorder traversal of BST prints nodes in ascending order.
After inserting 7, the inorder traversal visits nodes in sorted order: 2, 3, 5, 6, 7, 8, 9.