How to convert a binary tree to binary search tree in-place, i.e., we cannot use any extra space

前端 未结 11 1106
借酒劲吻你
借酒劲吻你 2021-01-31 22:12

How to convert a binary tree to binary search tree in-place, i.e., we cannot use any extra space.

11条回答
  •  迷失自我
    2021-01-31 22:42

    Do following algorithm to reach the solution.

    1) find the in order successor without using any space.

    Node InOrderSuccessor(Node node)
    { 
        if (node.right() != null) 
        { 
            node = node.right() 
            while (node.left() != null)  
                node = node.left() 
            return node 
        }
        else
        { 
            parent = node.getParent(); 
            while (parent != null && parent.right() == node)
           { 
                node = parent 
                parent = node.getParent() 
            } 
            return parent 
        } 
    } 
    

    2) Do in order traversal without using space.

    a) Find the first node of inorder traversal. It should left most child of the tree if it has, or left of first right child if it has, or right child itself. b) Use above algorithm for finding out inoder successor of first node. c) Repeat step 2 for all the returned successor.

    Use above 2 algorithm and do the in order traversal on binary tree without using extra space. Form the binary search tree when doing traversal. But complexity is O(N2) worst case.

提交回复
热议问题