leetcode-199. 二叉树的右视图

思路:打印每一层的最后一个节点即可。

/**
 * 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 {};
        queue<TreeNode*> q;
        vector<int> ans;
        q.push(root);
        int cnt=q.size();//cnt表示每一层的节点数
        while(!q.empty()){
            TreeNode *cur=q.front();
            q.pop();
            if(cur->left) q.push(cur->left);
            if(cur->right) q.push(cur->right);
             if(--cnt==0)
             {
                ans.push_back(cur->val); //只打印每层的最后一个节点
                cnt=q.size();//更新每层的节点数
             }
            
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/u014450222/article/details/85390762