Beispiel #1
0
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        # preorder root left right
        # inorder left root right

        if len(preorder) == 0:
            return None

        if len(preorder) == 1:
            return TreeNode(preorder[0])

        # find the root in the inorder
        in_root_idx = inorder.index(preorder[0])

        left_tree = self.buildTree(preorder[1:in_root_idx + 1],
                                   inorder[0:in_root_idx])
        right_tree = self.buildTree(preorder[in_root_idx + 1:],
                                    inorder[in_root_idx + 1:])

        tn = TreeNode(preorder[0])
        tn.left = left_tree
        tn.right = right_tree

        return tn
 def buildTree(self, preorder, inorder):
     # 128ms
     if inorder:
         ind = inorder.index(preorder.pop(0))
         root = TreeNode(inorder[ind])
         root.left = self.buildTree(preorder, inorder[0:ind])
         root.right = self.buildTree(preorder, inorder[ind + 1:])
         return root
Beispiel #3
0
 def helper(node: TreeNode, val: int):
     if node is None:
         node = TreeNode(val)
         return node
     if val < node.val:
         node.left = helper(node.left, val)
     else:
         node.right = helper(node.right, val)
     return node
 def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
     # 228ms
     if len(nums) == 0:
         return None
     i, n = self.maxnode(nums)
     node = TreeNode(n)
     node.left = self.constructMaximumBinaryTree(nums[:i])
     node.right = self.constructMaximumBinaryTree(nums[i + 1:])
     return node
Beispiel #5
0
 def dfs(node: TreeNode):
     if node is None:
         return None
     if node.left:
         node.left = dfs(node.left)
     if node.right:
         node.right = dfs(node.right)
     if node.val == target and node.left is None and node.right is None:
         node = None
     return node
 def sortedArrayToBST(self, nums):
     if nums == []:
         return None
     pos = len(nums) // 2
     node = TreeNode(nums[pos])
     if pos > 0:
         node.left = self.sortedArrayToBST(nums[0:pos])
     if pos > 0 and pos + 1 < len(nums):
         node.right = self.sortedArrayToBST(nums[pos + 1:])
     return node
Beispiel #7
0
 def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode:
     # 52ms
     if root is None:
         return None
     if root.left:
         root.left = self.removeLeafNodes(root.left, target)
     if root.right:
         root.right = self.removeLeafNodes(root.right, target)
     if root.val == target and root.left is None and root.right is None:
         root = None
     return root
    def arrayToBST(self, a):
        if len(a) == 0:
            return None
        if len(a) == 1:
            return TreeNode(a[0])

        mid = len(a) // 2
        tn = TreeNode(a[mid])
        left = self.arrayToBST(a[0:mid])
        right = self.arrayToBST(a[mid + 1:])
        tn.left = left
        tn.right = right
        return tn
 def insertIntoBST(self, root, val):
     # 124ms
     if root is None:
         return TreeNode(val)
     if val < root.val:
         if root.left is None:
             root.left = TreeNode(val)
         else:
             self.insertIntoBST(root.left, val)
     else:
         if root.right is None:
             root.right = TreeNode(val)
         else:
             self.insertIntoBST(root.right, val)
     return root
Beispiel #10
0
 def helper(var_n: int) -> List[Optional[TreeNode]]:
     if var_n in dp:
         return dp[var_n]
     result = []
     for i in range(1, var_n - 2 + 1):
         left_trees = helper(i)
         right_trees = helper(var_n - i - 1)
         for tree_l in left_trees:
             for tree_r in right_trees:
                 root = TreeNode()
                 root.left = tree_l
                 root.right = tree_r
                 result.append(root)
     dp[var_n] = result
     return result
Beispiel #11
0
 def setval(self, node):
     for i in range(len(self.results)):
         node.val = self.results[i]
         node.left = None
         if not node.right and i < len(self.results) - 1:
             node.right = TreeNode(0)
         node = node.right
 def construct(l, r):
     if l > r:
         return
     elif l == r:
         return TreeNode(nums[l])
     maximum = -float('inf')
     for i in range(l, r + 1):
         if maximum < nums[i]:
             maximum = nums[i]
             max_index = i
     left = construct(l, max_index - 1)
     right = construct(max_index + 1, r)
     root = TreeNode(maximum)
     root.left = left
     root.right = right
     return root
Beispiel #13
0
 def generate(left: int, right: int):
     if right - left < 0:
         return [None]
     elif right - left == 0:
         return [TreeNode(left)]
     else:
         res = []
         for curr in range(left, right + 1):
             leftChild = generate(left, curr - 1)
             rightChild = generate(curr + 1, right)
             for l in leftChild:
                 for r in rightChild:
                     root = TreeNode(curr)
                     root.left = l
                     root.right = r
                     res.append(root)
         return res
Beispiel #14
0
 def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
     # 216ms
     ans = []
     if n % 2 == 0: 
         return ans
     if n == 1:
         ans.append(TreeNode(0))
         return ans
     for i in range(1, n, 2):
         Ll = self.allPossibleFBT(i)
         Lr = self.allPossibleFBT(n - 1 - i)
         for node_l in Ll:
             for node_r in Lr:
                 node = TreeNode(0)
                 node.left = node_l
                 node.right = node_r
                 ans.append(node)
     return ans
 def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
     # 76ms
     if not root:
         return root
     if root.val > key:
         root.left = self.deleteNode(root.left, key)
     elif root.val < key:
         root.right = self.deleteNode(root.right, key)
     else:
         if not root.right:
             return root.left
         if not root.left:
             return root.right
         temp = root.right
         mini = temp.val
         while temp.left:
             temp = temp.left
             mini = temp.val
         root.val = mini
         root.right = self.deleteNode(root.right, root.val)
     return root
Beispiel #16
0
    def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: void
        """
        if self.get(key) != -1:

            self.head.val = (key, value)

        else:
            node = TreeNode((key, value))
            node.left = None
            node.right = self.head
            self.head.left = node
            self.head = node

            if self.tail.val[0] in self.h:
                del self.h[self.tail.val[0]]
            self.tail = self.tail.left
            self.tail.right = None

            self.h[self.head.val[0]] = self.head
Beispiel #17
0
 def addOneRowSub(root: TreeNode, v: int, d: int, n: int,
                  isLeft: bool) -> TreeNode:
     if root is None:
         return None
     if n == d:
         temp = root
         root = TreeNode(v)
         if isLeft:
             root.left = temp
         else:
             root.right = temp
     if root.left is not None:
         root.left = addOneRowSub(root.left, v, d, n + 1, True)
     elif n + 1 == d:
         root.left = TreeNode(v)
     if root.right is not None:
         root.right = addOneRowSub(root.right, v, d, n + 1, False)
     elif n + 1 == d:
         root.right = TreeNode(v)
     return root
Beispiel #18
0
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        # 40ms
        if not root:
            return
        self.prev = root
        self.flatten(root.left)

        temp = root.right
        root.right, root.left = root.left, None
        self.prev.right = temp

        self.flatten(temp)
Beispiel #19
0
    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """

        if len(inorder) == 0:
            return None
        if len(inorder) == 1:
            return TreeNode(inorder[0])
        # inorder left root right
        # postorder left right root
        n = len(postorder)
        root = postorder[n-1]
        root_idx = inorder.index(root)
        left_tree = self.buildTree(
            inorder[0:root_idx], postorder[0:root_idx])
        right_tree = self.buildTree(
            inorder[root_idx+1:], postorder[root_idx:-1])
        tn = TreeNode(root)
        tn.left = left_tree
        tn.right = right_tree
        return tn
    def helper(self, a):

        if len(a) == 1:
            return [TreeNode(a[0])]

        out = []
        for i in range(0, len(a)):
            if i == 0:
                lt = [None]
            else:
                lt = self.helper(a[0:i])

            if i == len(a) - 1:
                rt = [None]
            else:
                rt = self.helper(a[i + 1:])

            for ll in lt:
                for rr in rt:
                    root = TreeNode(a[i])
                    root.left = ll
                    root.right = rr
                    out.append(root)
        return out
Beispiel #21
0
    def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
        # 24ms
        if preorder is None:
            return None

        def helper(node: TreeNode, val: int):
            if node is None:
                node = TreeNode(val)
                return node
            if val < node.val:
                node.left = helper(node.left, val)
            else:
                node.right = helper(node.right, val)
            return node

        node = TreeNode(preorder[0])
        for i in range(1, len(preorder)):
            helper(node, preorder[i])
        return node
Beispiel #22
0
 def allPossibleFBT2(self, n: int) -> List[Optional[TreeNode]]:
     # 180ms
     dp = dict()
     dp[1] = [TreeNode()]
     def helper(var_n: int) -> List[Optional[TreeNode]]:
         if var_n in dp:
             return dp[var_n]
         result = []
         for i in range(1, var_n - 2 + 1):
             left_trees = helper(i)
             right_trees = helper(var_n - i - 1)
             for tree_l in left_trees:
                 for tree_r in right_trees:
                     root = TreeNode()
                     root.left = tree_l
                     root.right = tree_r
                     result.append(root)
         dp[var_n] = result
         return result
     return helper(n)
Beispiel #23
0
 def addOneRow2(self, root: TreeNode, v: int, d: int) -> TreeNode:
     # 48ms
     if d == 1:
         n = TreeNode(v)
         n.left = root
         return n
     dep = 1
     q = [root]
     while dep != d - 1:
         newq = []
         for n in q:
             if n.left:
                 newq.append(n.left)
             if n.right:
                 newq.append(n.right)
         q = newq
         dep += 1
     for n in q:
         l, r = n.left, n.right
         newl, newr = TreeNode(v), TreeNode(v)
         newl.left, newr.right = l, r
         n.left, n.right = newl, newr
     return root
Beispiel #24
0
    def __init__(self, capacity):
        """
        :type capacity: int
        """
        out = []

        for i in range(0, capacity):
            out.append(TreeNode(("num{}".format(i), None)))

        for i in range(0, capacity):
            if i == 0:
                out[i].left = None
            else:
                out[i].left = out[i - 1]
            if i == capacity - 1:
                out[i].right = None
            else:
                out[i].right = out[i + 1]

        self.head = out[0]
        self.tail = out[-1]
        self.h = {}
Beispiel #25
0
        path = []
        self.helper(root, sum, path, out)
        return out

    def helper(self, root, sum, path, out):
        if root is None:
            if sum == 0:
                out.append(path[:])
            return
        path.append(root.val)

        if root.left is None and root.right is None:
            if sum - root.val == 0:
                out.append(path[:])
        else:
            if root.left is not None:
                self.helper(root.left, sum - root.val, path, out)
            if root.right is not None:
                self.helper(root.right, sum - root.val, path, out)
        path.pop()
        return


test = False
if test:
    from TreeNode.TreeNode import arrayToTreeNode, TreeNode
    tn = arrayToTreeNode([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1])
    tmp = TreeNode(0)
    s = Solution()
    print(s.pathSum(tn, 22))
 def mergeTrees(self, t1, t2):
     if not t1 and not t2: return None
     ans = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0))
     ans.left = self.mergeTrees(t1 and t1.left, t2 and t2.left)
     ans.right = self.mergeTrees(t1 and t1.right, t2 and t2.right)
     return ans
    def mergeTrees_work(self, t1, t2):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        if t1 is None and t2 is None:
            return None
        elif t1 is not None and t2 is not None:
            node = TreeNode(t1.val + t2.val)
            node.left = self.mergeTrees(t1.left, t2.left)
            node.right = self.mergeTrees(t1.right, t2.right)
        elif t1 is not None:
            node = TreeNode(t1.val)
            node.left = self.mergeTrees(t1.left, None)
            node.right = self.mergeTrees(t1.right, None)
        elif t2 is not None:
            node = TreeNode(t2.val)
            node.left = self.mergeTrees(None, t2.left)
            node.right = self.mergeTrees(None, t2.right)

        return node