LC刷题专题:二叉树;迭代;递归(897、1372、208)

897.递增顺序搜索树

https://leetcode.cn/problems/increasing-order-search-tree/description/
在这里插入图片描述
这道题目本身就是一个简单题:非常容易实现:只需要在递归或者迭代中序遍历的同时保存一个临时节点,随后每遍历到一个节点,就把当前节点放到临时节点的右边,同时将临时节点更改为当前遍历到的节点。
迭代版本:

class Solution {
    TreeNode ans = new TreeNode();
    public TreeNode increasingBST(TreeNode root) {
        TreeNode res = ans;
        Deque<TreeNode> dq = new ArrayDeque<>();
        if(root == null){
            return ans;
        }
        TreeNode cur = root;
        while(!dq.isEmpty() || cur != null){
            if(cur != null){
                dq.addLast(cur);
                cur = cur.left;
            }else{
                cur = dq.pollLast();
                TreeNode temp = cur.right;
                cur.left = null;
                ans.right = cur;
                ans = cur;
                cur = temp;
            }
        }
        return res.right;
    }
}

递归版本:

class Solution {
    TreeNode ans = new TreeNode();
    public TreeNode increasingBST(TreeNode root) {
        TreeNode res = ans;
        buildIncrementTree(root);
        return res.right;
    }
    public void buildIncrementTree(TreeNode root){
        if(root == null){
            return;
        }
        buildIncrementTree(root.left);
        TreeNode cur = new TreeNode(root.val);
        ans.right = cur;
        ans = cur;
        buildIncrementTree(root.right);
    }
}

1372. 二叉树中的最长交错路径

参考我之前写过的一篇博客:
https://blog.csdn.net/weixin_45863010/article/details/139708882

208. 实现 Trie (前缀树)

参考之前文章:
https://blog.csdn.net/weixin_45863010/article/details/136297891

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值