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].
输出一棵树每层最右边的节点。这里我们最直接的就是每一层进行一次遍历,最终输出本层的最右边的元素即可,还有一种方法就是我们每一层只输出一个元素,我们从右子树开始遍历,存在右子树并且最终的序列中的个数小与层数,说明本层的节点没有加入进去,直接加入即可,跳到下一层就行,如果右子树不存在我们才遍历左子树,这种方法可以通过递归实现。两种方法的代码如下:
/**
* 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;
deque<TreeNode*> pre;
deque<TreeNode*> child;
pre.push_back(root);
while(!pre.empty())
{
TreeNode* node=pre.front();
pre.pop_front();
if(node->left)
{
child.push_back(node->left);
}
if(node->right)
{
child.push_back(node->right);
}
if(pre.empty())
{
res.push_back(node->val);
pre=child;
child.clear();
}
}
return res;
}
};class Solution {
public:
vector<int> res;
void rs(TreeNode* root,int level)
{
if(root==NULL) return;
if(res.size()<level) res.push_back(root->val);
rs(root->right,level+1);
rs(root->left,level+1);
}
vector<int> rightSideView(TreeNode* root) {
if(root==NULL) return res;
rs(root,1);
return res;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/sinat_24520925/article/details/47133553