-
题目链接 https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/comments/
-
题目描述
- 您需要在二叉树的每一行中找到最大的值。
-
输入: 1 / \ 3 2 / \ \ 5 3 9 输出: [1, 3, 9]
-
解题思路
- 通过二叉树的层次遍历求每一层的最大值,用队列实现即可。
- 需要注意的一点是如何当前遍历的元素是第几层,这里有三种方法, 设置哨兵、将节点加入队列的同时将节点的层次信息加入、确定每一层的长度并根据长度对每层循环
-
代码
- python(哨兵)
from collections import deque class Solution: def largestValues(self, root: TreeNode) -> List[int]: if not root: return [] last, curLast = root, None res, index = [root.val], 0 q = deque([root]) while q: tmp = q.popleft() res[index] = max(tmp.val, res[index]) if tmp.left: q.append(tmp.left) if tmp.right: q.append(tmp.right) curLast = tmp.right or tmp.left or curLast if tmp == last: index += 1 if q: res.append(curLast.val) last = curLast return res
- python(每层循环 这是在讨论区转的,然后进行稍加修改)
def largestValues(self, root): """ :type root: TreeNode :rtype: List[int] """ res=[] if root==None: return res l=[] l.append(root) while len(l)>0: _max=l[0].val for i in range(0,len(l)): temp_node=l[0] del l[0] , _max = max(temp_node.val,_max) if temp_node.left: l.append(temp_node.left) if temp_node.right: l.append(temp_node.right) res.append(max) return res
- python(哨兵)
leecode 515. 在每个树行中找最大值
最新推荐文章于 2020-09-10 17:15:31 发布