199. Binary Tree Right Side View

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

Hide Tags
  Tree Depth-first Search Breadth-first Search
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,C++,算法,遍历,搜索)