Leetcode 897. 递增顺序搜索树

897. 递增顺序搜索树

我以为我比较擅长递归,但是事实证明是迭代,我的脑子好像转不过来去理解抽象的东西。每次解题都是一个一步一步笨笨探索的过程。

给你一棵二叉搜索树,请你 按中序遍历 将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。

 

示例 1:

输入:root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

示例 2:

输入:root = [5,1,7]
输出:[1,null,5,null,7]

 

提示:

  • 树中节点数的取值范围是 [1, 100]
  • 0 <= Node.val <= 1000
/**
 * 迭代很慢
 */
class Solution {
    public TreeNode increasingBST(TreeNode root) {
        if(root==null)return null;
        TreeNode newRoot=null;
        TreeNode node=null;
        Stack<TreeNode> s=new Stack<TreeNode>();
        while(root!=null||!s.isEmpty()){
            while(root!=null){
                s.push(root);
                root=root.left;
            }
            root=s.pop();
            if(newRoot==null){
                newRoot=new TreeNode(root.val);
                node=newRoot;
            }else{
                node.right=new TreeNode(root.val);
                node=node.right;
            }
            root=root.right;
        }
        return newRoot;
    }
}

 

/*
    递归很好
*/
class Solution {
    TreeNode res;
    public TreeNode increasingBST(TreeNode root) {
        if(root==null)return null;
        TreeNode dummy=new TreeNode(-1);
        res=dummy;
        inorder(root);
        return dummy.right;
    }
    public void inorder(TreeNode root){
        if(root==null)return;
        inorder(root.left);
        res.right=root;
        root.left=null;
        res=res.right;
        inorder(root.right);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值