LeetCode 0314. Binary Tree Vertical Order Traversal Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0314. Binary Tree Vertical Order Traversal

Description

Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]

Example 2:

Input: root = [3,9,8,4,0,1,7]
Output: [[4],[9],[3,0,1],[8],[7]]

Example 3:

Input: root = [1,2,3,4,10,9,11,null,5,null,null,null,null,null,null,null,6]
Output: [[4],[2,5],[1,10,9,6],[3],[11]]

 

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Solutions

Solution 1: DFS

DFS traverses the binary tree, recording the value, depth, and horizontal offset of each node. Then sort all nodes by horizontal offset from small to large, then by depth from small to large, and finally group by horizontal offset.

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

PythonJavaC++Go
# 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 verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]: def dfs(root, depth, offset): if root is None: return d[offset].append((depth, root.val)) dfs(root.left, depth + 1, offset - 1) dfs(root.right, depth + 1, offset + 1) d = defaultdict(list) dfs(root, 0, 0) ans = [] for _, v in sorted(d.items()): v.sort(key=lambda x: x[0]) ans.append([x[1] for x in v]) return ans(code-box)

Solution 2: BFS

A better approach to this problem should be BFS, traversing from top to bottom level by level.

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

PythonJavaC++Go
# 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 verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]: if root is None: return [] q = deque([(root, 0)]) d = defaultdict(list) while q: for _ in range(len(q)): root, offset = q.popleft() d[offset].append(root.val) if root.left: q.append((root.left, offset - 1)) if root.right: q.append((root.right, offset + 1)) return [v for _, v in sorted(d.items())](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 !