funcrightSideView(root *TreeNode) []int { result := []int{} queue := []*TreeNode{root} n := 1 for n > 0 { for i := 0; i < n; i++ { node := queue[0] queue = queue[1:] if node != nil { if i == n - 1 { result = append(result, node.Val) } queue = append(queue, node.Left) queue = append(queue, node.Right) } } n = len(queue) } return result }
funcaverageOfLevels(root *TreeNode) []float64 { result := []float64{} queue := []*TreeNode{root} n := 1 for n > 0 { var sum float64 = 0 item := 0// Track the not nil item for i := 0; i < n; i++ { node := queue[0] queue = queue[1:] if node != nil { sum += float64(node.Val) item++ queue = append(queue, node.Left) queue = append(queue, node.Right) } } if item > 0 { result = append(result, sum / float64(item)) } n = len(queue) } return result }
funclargestValues(root *TreeNode) []int { result := []int{} if root != nil { queue := []*TreeNode{root} n := 1 for n > 0 { max := queue[0].Val for n > 0 { node := queue[0] queue = queue[1:] if node.Val > max { max = node.Val } if node.Left != nil { queue = append(queue, node.Left) } if node.Right != nil { queue = append(queue, node.Right) } n-- } n = len(queue) result = append(result, max) } } return result }
funcconnect(root *Node) *Node { if root != nil { queue := []*Node{root} n := 1 for n > 0 { for i := 0; i < n; i++ { if i > 0 { queue[i - 1].Next = queue[i] } if queue[i].Left != nil { queue = append(queue, queue[i].Left) queue = append(queue, queue[i].Right) } } queue = queue[n:] n = len(queue) } } return root }
b. DFS solution. Since the given tree is a full complete tree, we can easily use the parent node to get it’s siblings children nodes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcconnect(root *Node) *Node { parent := root for parent.Left != nil { // Has child node current := parent for current != nil { // Moving from left to right current.Left.Next = current.Right if current.Next != nil { current.Right.Next = current.Next.Left } current = current.Next } parent = parent.Left // Move to the next layer } return root }
funcconnect(root *Node) *Node { current := root for current != nil { dummy := &Node{} // Dummy pointer which points to the first node in current node's child layer tail := dummy // Using tail node to construct a linked list which head is dummy node for current != nil { if current.Left != nil { tail.Next = current.Left tail := tail.Next } if current.Right != nil { tail.Next = current.Right tail = tail.Next } current = current.Next } current = dummy.Next } return root }
funcgetDepth(node *TreeNode)int { if node != nil { left := getDepth(node.Left) right := getDepth(node.Right) if left > right { return left + 1 } return right + 1 } return0 }