[LeetCode] 897. Increasing Order Search Tree

45 篇文章 0 订阅

原题链接: https://leetcode.com/problems/increasing-order-search-tree/

1. 题目介绍

Given a binary search 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.
给出一个二叉搜索树,使用中序遍历的方法,对其进行重新排列。使得原树的最左的节点,变成新树的根节点,新树中,每一个节点只有右节点,没有左节点。

在这里插入图片描述
在这里插入图片描述
Note:
The number of nodes in the given tree will be between 1 and 100.
Each node will have a unique integer value from 0 to 1000.
节点的数量范围是[1 , 100]
每个节点的val值范围是[0 , 1000]

2. 解题思路

方法1 中序遍历+保存到List中

可以先中序遍历整个树,将结果保存在一个List中,之后再遍历这个List,将所有的节点值都存入一个新树中,返回新树。

实现代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode increasingBST(TreeNode root) {
        List<Integer> k = new ArrayList<>();
        buildTree( root, k);
        
        TreeNode pre = new TreeNode(0);
        TreeNode temp = pre;
        for(int i : k){
            temp.right = new TreeNode(i);
            temp = temp.right;
        }
        return pre.right;
    }
    public void buildTree(TreeNode root, List<Integer> k){
        if(root == null){
            return;
        }
        buildTree(root.left , k);
        k.add(root.val);
        buildTree(root.right , k);
    }
}

方法2 中序遍历+直接改变原来的树

仍然使用中序遍历的顺序,对所有的节点进行遍历。不过不需要像方法1一样新建一个List存放节点val值,而是直接修改原来的树,当遍历完一个节点的左子树后,就削去它的左子树,直接把这个节点作为一个新的节点放入树中。
实现代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    TreeNode pre = new TreeNode(0);
    TreeNode temp = pre;
    public TreeNode increasingBST(TreeNode root) {
        buildTree( root);

        return pre.right;
    }
    public void buildTree(TreeNode root){
        if(root == null){
            return;
        }
        buildTree(root.left);
        root.left = null;
        temp.right = root;
        temp = temp.right;
        buildTree(root.right);
    }
}

3. 参考资料

https://leetcode.com/problems/increasing-order-search-tree/solution/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值