Find Largest Value in Each Tree Row
Input:
1
/ \
3 2
/ \ \
5 3 9
Output:
[1, 3, 9]# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def largestValues(self, root: TreeNode) -> List[int]:
res = []
def dfs(root:TreeNode, d:int):
if not root:
return
if len(res) < d:
res.append(root.val)
elif res[d-1] < root.val:
res[d-1] = root.val
dfs(root.left,d+1)
dfs(root.right,d+1)
dfs(root,1)
return resLast updated