# STEP__2. now using for loop traverse the preorder array remaining elements from index 1'st not 0'th
#          now for every element(value) there will be two cases,
#          1. if it is smaller then stack top,
#             then it will be left child of stack top ,and insert it value into stack
#          2. if it is greater then stack top,
#             then get the next greater element(last) ,and make value its right child and append it to stack
# STEP__3. At last return root

def constructTree(preorderArray):
    stack = []

    root = BST.BinaryTreeNode(preorderArray[0])
    stack.append(root)

    for value in preorderArray[1:]:
        if value < stack[-1].data:
            new_left_node = BST.BinaryTreeNode(value)
            stack[-1].left = new_left_node
            stack.append(new_left_node)
        else:
            while stack and stack[-1].data < value:
                last = stack.pop()
            last.right = BST.BinaryTreeNode(value)
            stack.append(last.right)
    return root


preorder = [int(i) for i in input().strip().split()]
bstRoot = constructTree(preorder)
BST.PrintLevelWise(bstRoot)
        arr.append(arr2[j])
        j = j + 1
    return arr


# STEP 3:____________________________________________________________
def sortedArrayToBST(arr):
    if not arr:
        return None

    mid = len(arr) // 2

    root = BinaryTreeNode(arr[mid])

    root.left = sortedArrayToBST(arr[:mid])
    root.right = sortedArrayToBST(arr[mid + 1:])

    return root


root1 = BST.buildLevelTree()
root2 = BST.buildLevelTree()
arr1 = []
createSortedArray_from_BST(root1, arr1)
arr2 = []
createSortedArray_from_BST(root2, arr2)
arr = mergeSortedArray(arr1, arr2)
root = sortedArrayToBST(arr)

BST.PrintLevelWise(root)
Example #3
0
global prev


def flattenBSTHelper(curr):
    global prev
    if curr is None:
        return
    flattenBSTHelper(curr.left)
    prev.left = None
    prev.right = curr
    prev = curr
    flattenBSTHelper(curr.right)


def flattenBST(root):
    global prev
    if root is None:
        return
    dummy = BST.BinaryTreeNode(-1)
    prev = dummy
    flattenBSTHelper(root)
    prev.left = None
    prev.right = None
    ret = dummy.right
    return ret


root = BST.buildLevelTree()
newRoot = flattenBST(root)
BST.PrintLevelWise(newRoot)