题目:

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]​​.


思路分析:

二叉树的层次遍历,在遍历过程中输出每一层最右边的节点。

我们可以在层次遍历过程中先访问右边节点,然后访问做变节点,访问结果入队列,然后每一层最前边的节点放入结果集合中。


C++参考代码:

/**
* 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> rightSideView(TreeNode *root)
{
vector<int> result;
if (!root) return result;
queue<TreeNode*> nodeQueue;
TreeNode *node = root;
nodeQueue.push(node);
while (!nodeQueue.empty())
{
queue<TreeNode*>::size_type size = nodeQueue.size();
//每次依次取出这一层的节点,然后将改元素的左右节点入队列(如果是第一个节点,则放入结果集合中)
for (size_t i = 0; i < size; ++i)
{
node = nodeQueue.front();
nodeQueue.pop();
if (i == 0) result.push_back(node->val);
//注意是先右节点后左节点
if (node->right) nodeQueue.push(node->right);
if (node->left) nodeQueue.push(node->left);
}
}

return result;
}
};



C#参考代码:

/**
* Definition for binary tree
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public IList<int> RightSideView(TreeNode root)
{
IList<int> result = new List<int>();
if (root == null) return result;
Queue<TreeNode> nodeQueue = new Queue<TreeNode>();
TreeNode node = root;
nodeQueue.Enqueue(node);
while (nodeQueue.Count != 0)
{
int size = nodeQueue.Count;
for (int i = 0; i < size; ++i)
{
node = nodeQueue.Dequeue();
if (i == 0) result.Add(node.val);
if (node.right != null) nodeQueue.Enqueue(node.right);
if (node.left != null) nodeQueue.Enqueue(node.left);
}
}
return result;
}
}