给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例 1:

输入: [1,2,3,null,5,null,4] 输出: [1,3,4]
示例 2:
输入: [1,null,3] 输出: [1,3]
示例 3:
输入: [] 输出: []
c++解法
- class Solution {
- public:
- vector<int> rightSideView(TreeNode* root) {
- int depth=0;
- int h=0;
- vector<int> res;
- rightView(root,depth,0,res);
- return res;
- }
- void rightView(TreeNode* node,int& depth,int h,vector<int>& res)
- {
- if(node==nullptr) return;
- h++;
- if(h>depth)
- {
- res.push_back(node->val);
- depth++;
- }
- if(node->right)
- rightView(node->right,depth,h,res);
- if(node->left)
- rightView(node->left,depth,h,res);
- h--;
- }
- };
本题要输出二叉树的右视图,可利用递归的方法,将最右边的子树不断放入栈中,最后输出,每放入一次深度加一,得到即为所求答案
本题考察递归在二叉树上的应用,利用递归调用上一遍历的子树将所要求的数放入栈中,最后输出答案