Given 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:
Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
Related Topics:
Tree, Depth-first Search, Breadth-first Search, Recursion, Queue
Similar Questions:
// OJ: https://leetcode.com/problems/binary-tree-right-side-view/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(H)
class Solution {
vector<int> ans;
void dfs(TreeNode *root, int lv) {
if (!root) return;
if (lv == ans.size()) ans.push_back(root->val);
else ans[lv] = root->val;
dfs(root->left, lv + 1);
dfs(root->right, lv + 1);
}
public:
vector<int> rightSideView(TreeNode* root) {
dfs(root, 0);
return ans;
}
};