LeetCode——第十九天
199. 二叉树的右视图
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
分析:首先理解好题目,其实就是要按层输出每一层最右边的数字,按层很容易想到层次遍历,那只要增加一个数组每次存放最后那个节点的值就行了。
层次遍历代码
/**
* 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) {
//层次遍历的方法,每次输出访问最后一个元素
if(root==NULL) return {};
vector<int> res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int len = q.size();
for(int i=0;i<len;i++){
auto t = q.front();
q.pop();
if(i == len-1){
res.push_back(t->val);
}
if(t->left != NULL) q.push(t->left);
if(t->right != NULL) q.push(t->right);
}
}
return res;
}
};
层次遍历其实也就是广度优先遍历,我另一篇:岛屿数量
这里面就提到深度和广度,如果对这两个不熟悉,可以百度看看。
另外看了官方题解,这道题通过树的遍历同样的可以实现,遍历顺序为MRL即中右左,加一个深度做判断,每一个深度只有第一次访问才存入res中。
这里我是递归实现的,所以直接通过res的size来比较,省去存放深度的容器。而官方是非递归实现的,通过两个栈。
深度代码
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
//二叉树遍历的方法,深度遍历,顺序是每次先中右左,每一层第一次访问右时将该节点加入res
if(root==NULL) return {};
vector<int> res;
int level = 0;
dfs(root,level,res);
return res;
}
//深度遍历,这里通过res.size和level就可以知道是不是同一层,省去了再开辟一个空间存放level
void dfs(TreeNode *p,int level,vector<int>& res){
if(p==NULL) return;
if(res.size()==level) res.push_back(p->val);
dfs(p->right,level+1,res);
dfs(p->left,level+1,res);
}
};
官方代码
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
unordered_map<int, int> rightmostValueAtDepth;
int max_depth = -1;
stack<TreeNode*> nodeStack;
stack<int> depthStack;
nodeStack.push(root);
depthStack.push(0);
while (!nodeStack.empty()) {
TreeNode* node = nodeStack.top();nodeStack.pop();
int depth = depthStack.top();depthStack.pop();
if (node != NULL) {
// 维护二叉树的最大深度
max_depth = max(max_depth, depth);
// 如果不存在对应深度的节点我们才插入
if (rightmostValueAtDepth.find(depth) == rightmostValueAtDepth.end()) {
rightmostValueAtDepth[depth] = node -> val;
}
nodeStack.push(node -> left);
nodeStack.push(node -> right);
depthStack.push(depth + 1);
depthStack.push(depth + 1);
}
}
vector<int> rightView;
for (int depth = 0; depth <= max_depth; ++depth) {
rightView.push_back(rightmostValueAtDepth[depth]);
}
return rightView;
}
};