Given the root
of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example 1:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Explanation:
Example 2:
Input: root = [1,2,3,4,null,null,null,5]
Output: [1,3,4,5]
Explanation:
Example 3:
Input: root = [1,null,3]
Output: [1,3]
Example 4:
Input: root = []
Output: []
Constraints:
[0, 100]
.-100 <= Node.val <= 100
Problem Description:
Given the root of a binary tree, return the values of the nodes you can see ordered from top to bottom when standing on the right side of the tree.
Solutions:
Two approaches are presented to solve this problem: Breadth-First Search (BFS) and Depth-First Search (DFS). Both have a time complexity of O(N) and a space complexity of O(N), where N is the number of nodes in the tree.
This approach utilizes a queue to perform a level-order traversal. The rightmost node at each level is added to the result.
Algorithm:
ans
to store the results and a queue q
to store nodes for processing. Add the root node to the queue if it exists.ans
.Code (Python):
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def rightSideView(self, root: TreeNode) -> list[int]:
ans = []
if not root:
return ans
q = deque([root])
while q:
ans.append(q[0].val) # Add the rightmost node from previous level.
for _ in range(len(q)):
node = q.popleft()
if node.right:
q.append(node.right)
if node.left:
q.append(node.left)
return ans
Time and Space Complexity:
This approach uses recursion to traverse the tree. The key is to process the right subtree before the left subtree to ensure the rightmost node at each depth is visited first.
Algorithm:
ans
to store the results.dfs(root, depth)
:
root
is None, return.depth
is equal to the length of ans
, append the current node's value to ans
(this means we've reached a new level).dfs
on the right subtree first, then the left subtree.Code (Python):
class Solution:
def rightSideView(self, root: TreeNode) -> list[int]:
ans = []
def dfs(root, depth):
if not root:
return
if len(ans) == depth:
ans.append(root.val)
dfs(root.right, depth + 1)
dfs(root.left, depth + 1)
dfs(root, 0)
return ans
Time and Space Complexity:
Note: The code for other languages (Java, C++, Go, TypeScript, Rust, JavaScript) would follow similar logic and structure but with the appropriate syntax and data structures for each language. The provided problem statement includes these examples.