LeetCode 515 寻找二叉树每层的最大值

1 题目描述

该题目需要您找出二叉树中每一层的最大值,然后以数组返回。

例子:

输入:

          1
         / \
        3   2
       / \   \
      5   3   9

输出:[1, 3, 9]

题目出处: https://leetcode.com/problems/find-largest-value-in-each-tree-row/

2 解决思路

层次遍历二叉树,计算完一层,计算下一层,初始 root 即为一层。

3 Golang 实现代码

https://github.com/leileiluoluo/leetcode

func largestValues(root *TreeNode) []int {
	if nil == root {
		return []int{}
	}

	largestVals := []int{}
	children := []*TreeNode{root}
	for len(children) > 0 {
		tmp := children[:]
		children = []*TreeNode{}
		largest := -(1 << 32)
		for _, child := range tmp {
			if child.Val > largest {
				largest = child.Val
			}
			if nil != child.Left {
				children = append(children, child.Left)
			}
			if nil != child.Right {
				children = append(children, child.Right)
			}
		}
		largestVals = append(largestVals, largest)
	}
	return largestVals
}

评论

正在加载评论......