" "
You need to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
" "
# Definition for a binary tree node.
# class TreeNode (object):
# def __init__ (self, x):
# self.val = x
# self.left = None
# self.right = None
This title describes:
give us a binary tree root node that returns an array of the maximum values for each layer
thought:
breadth-first traversal, placing the maximum value of each layer into the result list
python implementations:
1 classsolution (object):2 deflargestvalues (self, root):3 """4 : Type Root:treenode5 : Rtype:list[int]6 """7 if notRoot:8 return []9levels =[[Root]]TenValues =[[Root.val]] One forLevelinchlevels: ANext_level = [] -Value = [] - forNodeinchLevel : the ifNode.left is notNone: - next_level.append (node.left) - value.append (node.left.val) - ifNode.right is notNone: + next_level.append (node.right) - value.append (node.right.val) + ifNext_level: A levels.append (next_level) at values.append (value) -res = [] - forVinchvalues: - res.append (Max (v)) - returnRes
Streamline the code:
1 classsolution (object):2 deflargestvalues (self, root):3 """4 : Type Root:treenode5 : Rtype:list[int]6 """7Values = []8Level =[Root]9 whileAny (level):TenValues.append (Max ([I.val forIinchLevel ]) ) Onelevel = [Child forNodeinchLevel forChildinch[Node.left, Node.right]ifChild is notNone] A returnValues
Leetcode algorithm: Find largest Value in each Tree Row