199. Binary Tree Right Side View
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 <---
题目链接:https://leetcode-cn.com/problems/binary-tree-right-side-view/
思路
法一:非递归
掌握层序遍历就很容易实现,只需要输出一层中最右的一个节点即可。
/**
* 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==NULL) return res;
queue<TreeNode*> record;
record.push(root);
while(!record.empty()){
int len = record.size();
res.push_back(record.back()->val);
for(int i=0; i<len; ++i){
auto tmp = record.front();
record.pop();
if(tmp->left) record.push(tmp->left);
if(tmp->right) record.push(tmp->right);
}
}
return res;
}
};
法二:递归
递归方法是看了分享理解的,自己本身还是没有很透彻理解递归。
主要有2个要点:
1.保证进入下一层时第一个访问的节点一定是最右:递归中先访问右边的节点,以此保证树在每次进入下一层时,第一个看到的一定是最右的节点,并将其记录。
2.如何判断该层是第一次进入:用记录结果vector的大小和层数之间的关系,相等说明是第一次进入(例如:根节点-第0层)。在次状态下所在节点就是第一个遇到的节点。
/**
* 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==NULL) return res;
goRight(0, root, res);
return res;
}
void goRight(int level, TreeNode* root, vector<int> &res){
if(root==NULL) return;
if(res.size()==level) res.push_back(root->val);
goRight(level+1, root->right, res);
goRight(level+1, root->left, res);
}
};

本文详细解析了LeetCode上二叉树右视图问题的两种解决方案:非递归和递归方法。通过层序遍历和递归策略,文章展示了如何从树的顶部到底部返回可以看到的节点值,特别强调了递归方法中节点访问顺序和层级判断的技巧。

被折叠的 条评论
为什么被折叠?



