Binary Tree Right Side View

https://leetcode.com/problems/binary-tree-right-side-view/

/**
 * 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> res;
        if(root==NULL)
            return res;
        queue<TreeNode *> q1,q2;
        q1.push(root);
        while(!q1.empty()||!q2.empty())
        {
            if(!q1.empty())
            {
                TreeNode * temp_num=q1.front();
                res.push_back(temp_num->val);
                while(!q1.empty())
                {
                    TreeNode * temp=q1.front();
                    q1.pop();
                    if(temp->right!=NULL)
                        q2.push(temp->right);
                    if(temp->left!=NULL)
                        q2.push(temp->left);
                }
            }
            else
            {
                TreeNode * temp_num=q2.front();
                res.push_back(temp_num->val);
                while(!q2.empty())
                {
                    TreeNode * temp=q2.front();
                    q2.pop();
                    if(temp->right!=NULL)
                        q1.push(temp->right);
                    if(temp->left!=NULL)
                        q1.push(temp->left);
                }
            }
        }
        return res;
    }
};

 

posted @ 2015-09-03 23:19  阿怪123  阅读(124)  评论(0编辑  收藏  举报