897. Increasing Order Search Tree

题目描述

Given a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.

在这里插入图片描述
在这里插入图片描述

方法思路

Approach1:

class Solution {
    //Runtime: 27 ms, faster than 69.38%
    //Memory Usage: 47.9 MB, less than 5.37%
    //不知道为什么,只能List<Integer>,不能List<TreeNode>,否则就会超时,感觉怪怪的
    private  list = new LinkedList<>();
    public TreeNode increasingBST(TreeNode root) {
        if(root == null) return root;
        inorder(root);
        TreeNode ans = new TreeNode(0);
        TreeNode cur = ans;
        for(int x : list){
            cur.right = new TreeNode(x);
            cur = cur.right;
        }
        return ans.right;
    }
    
    public void inorder(TreeNode root){
        if(root == null) return;
        inorder(root.left);
        list.add(root.val);
        inorder(root.right);
    }
}

Approach2:
We can perform the same in-order traversal as in Approach 1. During the traversal, we’ll construct the answer on the fly, reusing the nodes of the given tree by cutting their left child and adjoining them to the answer.

class Solution {
    //Runtime: 24 ms, faster than 96.86% 
    //Memory Usage: 46.3 MB, less than 31.42%
    TreeNode cur;
    public TreeNode increasingBST(TreeNode root) {
        TreeNode ans = new TreeNode(0);
        cur = ans;
        inorder(root);
        return ans.right;
    }

    public void inorder(TreeNode node) {
        if (node == null) return;
        inorder(node.left);
        node.left = null;
        cur.right = node;
        cur = node;
        inorder(node.right);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值