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].
https://leetcode.com/problems/binary-tree-right-side-view/ 题目位置
其实就是层序遍历,然后记录每一层中节点,最后一个的值
经常做到和层序相关的题目,之前是一个二叉树的Z扫描的问题,和这里基本上才用了一样的数据结构,所以很熟悉,写完就AC。
利用了一个vector存储每一层的元素,然后进行一个简单的递归
如果二叉树中没有对每一行有特别需要的要求,那么就是可以直接利用 队列,如果有要求,也可以在队列中加入一个类似NULL节点表示结束
http://blog.csdn.net/xietingcandice/article/details/44939919
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> res;
vector<int> rightSideView(TreeNode *root) { //其实就是每一行的最后一个节点
res.clear();
if(root == NULL)
{
return res;
}
vector<TreeNode*> node;
node.push_back(root);
GetNum(node);
return res;
}
void GetNum(vector<TreeNode*> &node)
{
if(node.empty())
{
return;
}
vector<TreeNode*>pNode;
//<获取当前层最右边节点的值
res.push_back(node[node.size()-1]->val);
//<按顺序获取他的子节点
for(int i = 0; i < node.size();i++)
{
TreeNode * root = node[i];
if(root->left)
{
pNode.push_back(root->left);
}
if(root->right)
{
pNode.push_back(root->right);
}
}
GetNum(pNode);
}
};Binary Tree Right Side View 二叉树层序遍历变形
原文:http://blog.csdn.net/xietingcandice/article/details/44997293