199. 二叉树的右视图
思路:递归每次都优先右边子树,然后才是左子树。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
//root:当前根节点、d:当前深度
void dfs(TreeNode* root,int d,vector<int> & depth,vector<int> & visit){
//为空直接返回
if(root==nullptr) return;
//当前深度第一次出现
if(!depth[d]){
depth[d]=1;
visit.push_back(root->val);
}
//右子树
dfs(root->right,d+1,depth,visit);
//左子树
dfs(root->left,d+1,depth,visit);
}
vector<int> rightSideView(TreeNode* root) {
//记录每个深度是否已有节点被看见
vector<int> depth(105,0);
vector<int> visit;//记录被看见的节点
//递归
dfs(root,0,depth,visit);
return visit;
}
};
优化一下空间。每次插入节点值时,其实都是遇见了一个新的深度,即:visit.size()==d。因此不需要数组depth。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* root,int d,vector<int> & visit){
if(root==nullptr) return;
//优化
if(visit.size()==d){
visit.push_back(root->val);
}
dfs(root->right,d+1,visit);
dfs(root->left,d+1,visit);
}
vector<int> rightSideView(TreeNode* root) {
vector<int> visit;
dfs(root,0,visit);
return visit;
}
};
标签:right,TreeNode,nullptr,visit,dfs,视图,二叉树,root,left
From: https://blog.csdn.net/weixin_46028214/article/details/142414589