2023年2月7日 星期二

199. Binary Tree Right Side View

解題思路

一次檢查一個 level,每次都先把最右邊的紀錄下來,其他的把左右子節點放進 queue。

程式碼

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> ans;
        if(!root) return ans;

        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty())
        {
            ans.push_back(q.back()->val);
            int size = q.size();
            for(int i=0; i<size; i++)
            {
                if(q.front()->left) q.push(q.front()->left);
                if(q.front()->right) q.push(q.front()->right);
                q.pop();
            }
        }
        return ans;
    }
};

沒有留言:

張貼留言