LeetCode暑期刷题打卡——树专题day5

173. 二叉搜索树迭代器

在这里插入图片描述

  • 用栈来实现迭代
stack<TreeNode*> stk;
    BSTIterator(TreeNode* root) {
        while(root){
            stk.push(root);
            root = root->left;
        }
    }
    
    int next() {
        auto p = stk.top();
        stk.pop();
        int val = p->val;
        p = p->right;
        while(p){
            stk.push(p);
            p=p->left;
        }
        return val;
    }
    
    bool hasNext() {
        return !stk.empty();
    }

297. 二叉树的序列化与反序列化

在这里插入图片描述


    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string res;
        dfs1(root,res);
        return res;
    }

    void dfs1(TreeNode* root,string &res){
        if(!root){
            res += "#,";
            return ;
        }
        res += to_string(root->val) + ",";
        dfs1(root->left,res);
        dfs1(root->right,res);
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        int u = 0;
        return dfs2(data,u);
    }

    TreeNode* dfs2(string &data,int &u){
        if(data[u] == '#'){
            u += 2;
            return NULL;
        }
        int t = 0;
        bool is_minus = false;
        if(data[u] == '-'){
            is_minus = true;
            u ++;
        }
        while(data[u] != ','){
            t = t * 10 + data[u] - '0';
            u ++;
        }
        u ++;
        if(is_minus) t = -t;
        auto root = new TreeNode(t);
        root->left = dfs2(data,u);
        root->right = dfs2(data,u);
        return root;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值