Leetcode 1040 Solution

This article provides solution to leetcode question 1040 (maximum-binary-tree-ii)

https://leetcode.com/problems/maximum-binary-tree-ii

Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode:
        dummy_node = TreeNode(right=root)
        prev_node = dummy_node
        curr_node = root

        while curr_node is not None:
            if curr_node.val < val:
                insert_node = TreeNode(val, curr_node)
                prev_node.right = insert_node
                break
            else:
                prev_node = curr_node
                curr_node = curr_node.right
        else:
            prev_node.right = TreeNode(val, curr_node)

        return dummy_node.right