Increasing Order Search Tree

Problem Id: 897 Difficulty: Easy Tag: Tree Tag: Depth-first Search


Intuition

Just do an inorder and nodify each node after visiting this node.

Solution


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def increasingBST(self, root: TreeNode) -> TreeNode:
        self.last = None
        self.root = None
        self._dfs(root)
        if self.last:
            self.last.left = self.last.right = None
        return self.root

    def _dfs(self, node):
        if node is None:
            return

        self._dfs(node.left)
        if self.last is None:
            self.root = node
        last = self.last
        self.last = node
        self._dfs(node.right)

        if last is not None:
            last.right = node
            last.left = None