0515-Find Largest Value in Each Tree Row

題目如下:

Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

只求 pass 的解答。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func largestValues(root *TreeNode) []int {
	if root == nil {
		return []int{}
	}

	var ans []int
	var checkNodes []*TreeNode
	checkNodes = append(checkNodes, root)
	for {
		if len(checkNodes) == 0 {
			break
		}
		var values []int
		var tmp []*TreeNode
		for _, n := range checkNodes {
			if n != nil {
				values = append(values, n.Val)
				if n.Left != nil {
					tmp = append(tmp, n.Left)
				}
				if n.Right != nil {
					tmp = append(tmp, n.Right)
				}
			}
		}
		ans = append(ans, max(values))
		checkNodes = tmp
	}
	return ans
}

func max(values []int) int {
	m := values[0]
	for i := 1; i < len(values); i++ {
		if m < values[i] {
			m = values[i]
		}
	}
	return m
}
updatedupdated2021-06-172021-06-17