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

<LeetCode OJ> 199. Binary Tree Right Side View

时间:2016-04-29 18:57:13      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

Total Accepted: 40438 Total Submissions: 117654 Difficulty: Medium

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

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Show Similar Problems

分析:

典型的广度优先遍历,每一层的最右边那个元素显然就是当层的右视可见节点!

/**
 * 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) {
        if(root==NULL)  
            return result;  
        queue<TreeNode *> que;  
        que.push(root);  
        //广度优先,总是压入每一层最右边的即可
        while(!que.empty())  
        {  
            int levelNum = que.size();//通过size来判断当层的结束   
            for(int i=0; i<levelNum; i++)     
            {    
                if(que.front()->left != NULL) //先获取该节点下一层的左右子,再获取该节点的元素,因为一旦压入必弹出,所以先处理左右子    
                    que.push(que.front()->left);    
                if(que.front()->right != NULL)     
                    que.push(que.front()->right);    
                if(i== (levelNum-1))        
                    result.push_back(que.front()->val);    
                que.pop();    
            }
            
        }  
        return result;  
    }
private:
     vector<int> result;
};




注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51236061

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

<LeetCode OJ> 199. Binary Tree Right Side View

标签:

原文地址:http://blog.csdn.net/ebowtang/article/details/51236061

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