【Leetcode】897. Increasing Order Search Tree

Title address:

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

Given a binary search tree, flatten it into a monotonically increasing linked list, and the next of the linked list is specified as the right of TreeNode.

Law 1: Divide and conquer. First convert the left and right subtrees to a linked list. Because it is a binary search tree, the left and right subtrees are monotonically increased linked lists. Then connect the right of the tree root as the tail node of the left subtree, and then return to the left subtree root. Of course, if the left subtree is empty, simply return to the root of the tree. code show as below:

public class Solution {
    public TreeNode increasingBST(TreeNode root) {
        // 如果是空树,则直接返回null
        if (root == null) {
            return null;
        }
        // 先把左子树flatten
        TreeNode left = increasingBST(root.left);
        // 接下来把左子树断开
        root.left = null;
        // 将右子树flatten后接在树根右边
        root.right = increasingBST(root.right);
        // 如果左子树是空树,那就直接返回root即可
        if (left == null) {
            return root;
        }
        // 否则将左子树的尾结点找到,然后接到root前面
        TreeNode leftTail = left;
        while (leftTail.right != null) {
            leftTail = leftTail.right;
        }
        leftTail.right = root;
        
        return left;
    }
}

class TreeNode {
    int val;
    TreeNode left, right;
    
    TreeNode(int x) {
        val = x;
    }
}

time complexity THE ( n 2 ) O (n ^ 2) (The reason is that each time you have to traverse the left subtree to the end), the space THE ( h ) O(h)

Method 2: Simply traverse in sequence. code show as below:

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public TreeNode increasingBST(TreeNode root) {
        List<TreeNode> list = new ArrayList<>();
        inorder(root, list);
        if (list.isEmpty()) {
            return null;
        }
        
        // 注意要将左子树清空
        TreeNode res = list.get(0), cur = res;
        res.left = null;
        for (int i = 1; i < list.size(); i++) {
            cur.right = list.get(i);
            cur.left = null;
            cur = cur.right;
        }
        
        return res;
    }
    
    private void inorder(TreeNode root, List<TreeNode> list) {
        if (root == null) {
            return;
        }
        
        inorder(root.left, list);
        list.add(root);
        inorder(root.right, list);
    }
}

Space-time complexity THE ( n ) O (n)

Published 388 original articles · liked 0 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/105340634