leetcode 897

Increasing Order Search Tree

def increasingBST(self, root, tail = None):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return tail
        res = self.increasingBST(root.left, root)
        root.left = None
        root.right = self.increasingBST(root.right, tail)
        return res

大概意思就是root.left.right = root, root.left = Null ? 但是不理解怎么写, 为什么这么写

你先写下tree的 inorder traversal

看solution

class Solution {
    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);
    }
}

1 Like