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;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章