题目描述
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 <—
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-right-side-view
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
深度优先搜索
如果按正确的顺序访问每个节点,就可以有效地获得二叉树的右视图。
上面提到的顺序之一可以由深度优先搜索定义。在深度优先搜索中,我们总是先访问右子树。这样就保证了当我们访问树的某个特定深度时,我们正在访问的节点总是该深度的最右侧节点。于是,可以存储在每个深度访问的第一个结点,一旦我们知道了树的层数,就可以得到最终的结果数组。
#include <iostream>
#include <vector>
using namespace std;
/// DFS
/// Time Complexity: O(n)
/// Space Complexity: O(h)
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
private:
vector<int> res;
public:
vector<int> rightSideView(TreeNode* root) {
if(!root) return res;
dfs(root, 0);
return res;
}
private:
void dfs(TreeNode* node, int d){
if(res.size() <= d) res.push_back(0);
res[d] = node->val;
if(node->left) dfs(node->left, d + 1);
if(node->right) dfs(node->right, d + 1);
}
};
int main() {
return 0;
}
思路二
广度优先搜索
就像深度优先搜索可以保证我们最先访问某个深度的最右结点那样,广度优先搜索可以保证我们 最后 访问它。
通过执行将左结点排在右结点之前的广度优先搜索,我们对每一层都从左到右访问。因此,通过只保留每个深度最后访问的结点,我们就可以在遍历完整棵树后得到每个深度最右的结点
#include <iostream>
#include <vector>
using namespace std;
/// BFS
/// Time Complexity: O(n)
/// Space Complexity: O(n)
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
if(!root) return res;
vector<TreeNode*> cur = {root};
while(cur.size()){
res.push_back(cur.back()->val);
vector<TreeNode*> next;
for(TreeNode* node: cur){
if(node->left) next.push_back(node->left);
if(node->right) next.push_back(node->right);
}
cur = next;
}
return res;
}
};
int main() {
return 0;
}