199. 二叉树的右视图

题目描述:

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---


思路:使用一个队列,做层次遍历,每次都把下一层的节点保存在这个队列里面,那么这个队列最右边的节点就是站在右边可以看到的节点

代码:

/**
 * 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) {
        vector<int> ret;
        if(root == NULL)
            return ret;
        
        queue<TreeNode* > next_q;
        if(root->left != NULL)
            next_q.push(root->left);
        if(root->right != NULL)
            next_q.push(root->right);
        
        ret.push_back(root->val);
        while(!next_q.empty()){
            ret.push_back(next_q.back()->val);
            queue<TreeNode* > temp_q;
            
            while(!next_q.empty()){
                TreeNode* tempNode = next_q.front();
                if(tempNode->left != NULL)
                    temp_q.push(tempNode->left);
                if(tempNode->right != NULL)
                    temp_q.push(tempNode->right);
                next_q.pop();
            }
            
            next_q = temp_q;
            
        }
        
        return ret;     
    }
};

猜你喜欢

转载自blog.csdn.net/sinat_15723179/article/details/81061954