码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Binary Tree Right Side View

时间:2015-04-06 15:43:56      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:leetcode   二叉树   遍历   

题目:

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;
    }
}


Leetcode: Binary Tree Right Side View

标签:leetcode   二叉树   遍历   

原文地址:http://blog.csdn.net/theonegis/article/details/44902247

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!