一、问题描述
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.
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return [1, 3, 4]
.
二、思路
本题意在求出最右侧的节点,从上到下存储在数组中返回。二叉树的题目用递归是上上策,本题中递归的退出条件是:
if(!node){
return ;
}
其中代码的灵魂是:
if(level >= vec.size())
vec.push_back(node -> val);
如果我们的层高不小于数组的容量,那么需要将当前值放入,意味着这个节点是最右节点。
递归的顺序也很重要,因为是存储最右边的,所以我们先递归右子树,如果右子树为空才去递归左子树。
三、代码
/**
* 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:
void storeSide(TreeNode* node,int level,vector<int> &vec){
if(!node){
return ;
}
if(level >= vec.size())
vec.push_back(node -> val);
storeSide(node -> right,level + 1,vec);
storeSide(node -> left,level + 1,vec);
}
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
storeSide(root,0,res);
return res;
}
};