Leetcode

Binary Tree Right Side View

Approach 1: BFS

  • Time:O(n)
  • Space:O(n)

C++

class Solution {
 public:
  vector<int> rightSideView(TreeNode* root) {
    if (!root)
      return {};

    vector<int> ans;
    queue<TreeNode*> q{{root}};

    while (!q.empty()) {
      const int size = q.size();
      for (int i = 0; i < size; ++i) {
        TreeNode* node = q.front();
        q.pop();
        if (i == size - 1)
          ans.push_back(node->val);
        if (node->left)
          q.push(node->left);
        if (node->right)
          q.push(node->right);
      }
    }

    return ans;
  }
};

JAVA

class Solution {
  public List<Integer> rightSideView(TreeNode root) {
    if (root == null)
      return new ArrayList<>();

    List<Integer> ans = new ArrayList<>();
    Queue<TreeNode> q = new ArrayDeque<>(Arrays.asList(root));

    while (!q.isEmpty()) {
      final int size = q.size();
      for (int i = 0; i < size; ++i) {
        TreeNode node = q.poll();
        if (i == size - 1)
          ans.add(node.val);
        if (node.left != null)
          q.offer(node.left);
        if (node.right != null)
          q.offer(node.right);
      }
    }

    return ans;
  }
}

Python

class Solution:
  def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
    if not root:
      return []

    ans = []
    q = deque([root])

    while q:
      size = len(q)
      for i in range(size):
        root = q.popleft()
        if i == size - 1:
          ans.append(root.val)
        if root.left:
          q.append(root.left)
        if root.right:
          q.append(root.right)

    return ans

Approach 2: DFS

  • Time:O(n)
  • Space:O(h)

C++

class Solution {
 public:
  vector<int> rightSideView(TreeNode* root) {
    vector<int> ans;
    dfs(root, 0, ans);
    return ans;
  }

 private:
  void dfs(TreeNode* root, int depth, vector<int>& ans) {
    if (!root)
      return;

    if (depth == ans.size())
      ans.push_back(root->val);
    dfs(root->right, depth + 1, ans);
    dfs(root->left, depth + 1, ans);
  }
};

JAVA

class Solution {
  public List<Integer> rightSideView(TreeNode root) {
    List<Integer> ans = new ArrayList<>();
    dfs(root, 0, ans);
    return ans;
  }

  private void dfs(TreeNode root, int depth, List<Integer> ans) {
    if (root == null)
      return;

    if (depth == ans.size())
      ans.add(root.val);
    dfs(root.right, depth + 1, ans);
    dfs(root.left, depth + 1, ans);
  }
}

Python

class Solution:
  def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
    ans = []

    def dfs(root: Optional[TreeNode], depth: int) -> None:
      if not root:
        return

      if depth == len(ans):
        ans.append(root.val)
      dfs(root.right, depth + 1)
      dfs(root.left, depth + 1)

    dfs(root, 0)
    return ans