[LeetCode 199] 二叉树的右视图

199. 二叉树的右视图

宽搜解决
解析在2h20min处

#include 
#include 
#include 
#include 
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
    public:
        vector rightSideView(TreeNode* root) {
            vectorres;
            TreeNode *cur;
            queue >q;
            if(root) q.push(make_pair(root,0));
            while(!q.empty()) {
                cur=q.front().first;
                int depth=q.front().second;
                q.pop();

                if(res.size()==depth)
                    res.push_back(cur->val);
                else res[depth]=cur->val;
                if(cur->left)
                    q.push(make_pair(cur->left,depth+1));
                if(cur->right)
                    q.push(make_pair(cur->right,depth+1));

            }
            return res;
        }
};


int main() {
    TreeNode *a1 = new TreeNode(1);
    TreeNode *b1 = new TreeNode(2);
    TreeNode *b2 = new TreeNode(3);
    TreeNode *c1 = new TreeNode(123);
    TreeNode *c2 = new TreeNode(5);
    TreeNode *c3 = new TreeNode(4);

    a1->left = b1;
    a1->right = b2;
    b1->left = c1;
    b1->right = c2;
    b2->right = c3;
    Solution s;
    vectorres=s.rightSideView(a1);
    for(int i=0;i

你可能感兴趣的:([LeetCode 199] 二叉树的右视图)