199 Binary Tree Right Side View

199. Binary Tree Right Side View

1. Question

Given a binary tree, imagine yourself standing on therightside of it, return the values of the nodes you can see ordered from top to bottom.

For example: Given the following binary tree,

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

You should return[1, 3, 4].

2. Implementation

(1) DFS

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

        if (root == null) {
            return res;
        }

        getRightSideView(root, 0, res);
        return res;
    }

    public void getRightSideView(TreeNode node, int depth, List<Integer> res) {
        if (node == null) {
            return;
        }

        if (res.size() == depth) {
            res.add(node.val);
        }

        getRightSideView(node.right, depth + 1, res);
        getRightSideView(node.left, depth + 1, res);
    }
}

(2) BFS

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

        if (root == null) {
            return res;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.remove();

                if (i == size - 1) {
                    res.add(curNode.val);
                }

                if (curNode.left != null) {
                    queue.add(curNode.left);
                }

                if (curNode.right != null) {
                    queue.add(curNode.right);
                }
            }
        }
        return res;
    }
}

3. Time & Space Complexity

DFS: 时间复杂度是O(n), 空间复杂度是O(n)

BFS: 时间复杂度是O(n), 空间复杂度是O(w),w为一层里最多node的个数

Last updated