Contents

# 515. 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).

### Example :

Note

Example 1:

Input: root = [1,3,2,5,3,null,9] Output: [1,3,9]

Example 2:

Input: root = [1,2,3] Output: [1,3]

Example 3:

Input: root = [1] Output: [1]

Example 4:

Input: root = [1,null,2] Output: [1,2]

Example 5:

Input: root = [] Output: []

#### 解題思路 :

• 這題是level order traversal的變化題，一樣可以用queue來解決，可以參考 leetcode102題解
• 這類題目解法都差不多，需要要每個level 最大的value取出來就ok了!

### Queue解法

• time complexity: O(n) , space complexity: O(n)

Runtime: 4 ms, faster than 98.39% of Go online submissions for Find Largest Value in Each Tree Row.

 `````` 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 49 50 51 52 `````` ``````/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func largestValues(root *TreeNode) []int { var res []int if root == nil { return res } var queue []*TreeNode queue = append(queue,root) for len(queue) != 0 { length := len(queue) max := queue[0].Val for i := 0; i < length; i++ { node := queue[0] 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) } queue = queue[1:] } res = append(res, max) } return res } ``````