面试必考精华版Leetcode199. 二叉树的右视图

题目:

面试必考精华版Leetcode199. 二叉树的右视图_第1张图片


代码(首刷看解析):

class Solution {
public:
    vector rightSideView(TreeNode* root) {
        unordered_map rightmostvalue;
        queue nodeQueue;
        queue depthQueue;
        int maxDepth=-1;

        nodeQueue.push(root);
        depthQueue.push(0);
        while(!nodeQueue.empty()){
            TreeNode* node = nodeQueue.front();nodeQueue.pop();
            int depth = depthQueue.front();depthQueue.pop();
            

            if(node!=nullptr){
                maxDepth = max(maxDepth,depth);
                //下面这一行运用了unordered_map的特性更新,直到最右值
                rightmostvalue[depth]=node->val;

                nodeQueue.push(node->left);
                nodeQueue.push(node->right);
                depthQueue.push(depth+1);
                depthQueue.push(depth+1);
            }
        }

        vector ans;
        for(int i=0;i<=maxDepth;++i){
            ans.push_back(rightmostvalue[i]);
        }
        return ans;
    }
};

你可能感兴趣的:(#,leetcode,---medium,前端,算法,javascript)