LeetCode 0515. Find Largest Value in Each Tree Row Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0515. Find Largest Value in Each Tree Row

Description

Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

 

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]

 

Constraints:

  • The number of nodes in the tree will be in the range [0, 104].
  • -231 <= Node.val <= 231 - 1

Solutions

Solution 1: BFS

We define a queue q and put the root node into the queue. Each time, we take out all the nodes of the current level from the queue, find the maximum value, and then put all the nodes of the next level into the queue until the queue is empty.

The time complexity is O(n), and the space complexity is O(n). Here, n is the number of nodes in the binary tree.

PythonJavaC++GoTypeScriptRust
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def largestValues(self, root: Optional[TreeNode]) -> List[int]: ans = [] if root is None: return ans q = deque([root]) while q: x = -inf for _ in range(len(q)): node = q.popleft() x = max(x, node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) ans.append(x) return ans(code-box)

Solution 2

PythonJavaC++GoTypeScriptRust
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def largestValues(self, root: Optional[TreeNode]) -> List[int]: def dfs(root, curr): if root is None: return if curr == len(ans): ans.append(root.val) else: ans[curr] = max(ans[curr], root.val) dfs(root.left, curr + 1) dfs(root.right, curr + 1) ans = [] dfs(root, 0) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !