Description

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 <---

分析一

题目的意思是:假设我从右边看二叉树,返回我能看见的二叉树节点,自顶向下输出。

  • 宽度优先搜索的核心就是队列,注意这个解法很常见,这道题的核心就是每次层序遍历返回最后一个值就行了。

代码- BFS

/**
* 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;
}
queue<TreeNode*> q;
q.push(root);
TreeNode* t;
while(!q.empty()){
int n=q.size();
for(int i=0;i<n;i++){
t=q.front();
q.pop();
if(t->left){
q.push(t->left);
}
if(t->right){
q.push(t->right);
}
}
res.push_back(t->val);
}
return res;
}
};

分析二

  • 这个DFS的解法可以说是非常的巧妙了,代码很直观,看不懂就模拟一下,核心讲解已经写在代码里面了。

代码二- DFS

/**
* 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> views;
scan(root, 0, views);
return views;
}
private:
void scan(TreeNode* root, int h, vector<int>& views)
{
if(!root) return;
if(h >= views.size())
views.emplace_back(root->val);
/* 先遍历右侧,这样就可以先选择右边的元素 */
scan(root->right, h + 1, views);
scan(root->left, h + 1, views);
}
};

参考文献

​每天一道LeetCode-----从右向左观察一棵二叉树,返回能看到的元素​