//DFS solution classSolution { public: vector<int> rightSideView(TreeNode* root) { vector<int> res; helper(res, root, 0); return res; } voidhelper(vector<int>& res, TreeNode* cur, int depth){ if(!cur) return; if(depth == res.size()){ res.push_back(cur->val); } helper(res, cur->right, depth+1); helper(res, cur->left, depth+1); //if a root have right and left node, the right node will add to res already, so left will not be pushed into res. } };
time complexity: O(n) space complexity: O(n)
BFS solution:
for BFS, we traverse each level with a queue.
push the newest element in queue to res. That is because the way we traverse, will look like this.
1 2 3
1 2 3 4 5 6 7
queue: 7 6 5 4, 4 will be pushed into queue first, 7 will be the last and right most element.
BFS python Use deque to store node in each level, then append child nodes in new deque. The idea is to push the right most node last, so it would make sure stack[-1] is the rightest one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: defrightSideView(self, root: TreeNode) -> List[int]: deque = collections.deque() if root: deque.append(root) res = [] while deque: newStack = collections.deque() res.append(deque[-1].val) for _ in range(len(deque)): node = deque.popleft() if node.left: newStack.append(node.left) if node.right: newStack.append(node.right) deque = newStack return res