Leetcode 199. 二叉树的右视图 C++

题目描述

在这里插入图片描述

思路

这个题需要注意的是,当左子树的深度比右子树大得多的情况,所以不能只考虑树的右边。题目所给的例子带有一点误导性。本题采用的方法仍然是树的层序历遍,真的是一招学好,走遍天下。通过一个队列控制,每次处理一层的节点,同时将下一层的节点压入队列。当处理到当层的最后一个节点的时候,将这个节点的值压入保存最终结果的vector中。于是就可以得到结果。

解答

/**
 * 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) return res;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty())
        {
            auto size = q.size();
            while(size--)
            {
                TreeNode* temp = q.front();
                q.pop();
                if(0 == size) res.push_back(temp->val);
                if(temp->left) q.push(temp->left);
                if(temp->right) q.push(temp->right);
            }
        }
        return res;
        
    }
};

猜你喜欢

转载自blog.csdn.net/yuanliang861/article/details/84559789