Ejemplo n.º 1
0
 def pasteChildren(pointer: TreeNode) -> List[TreeNode]:
     result = []
     if pointer:
         if pointer.left:
             result.append(TreeNode(pointer.val + pointer.left.val, pointer.left.left, pointer.left.right))
         if pointer.right:
             result.append(TreeNode(pointer.val + pointer.right.val, pointer.right.left, pointer.right.right))
     return result
Ejemplo n.º 2
0
 def buildChildTree(pre_l: int, pre_r: int, ino_l: int, ino_r: int) -> TreeNode or None:
     root = None
     if pre_l <= pre_r:
         root = TreeNode(preorder[pre_l])
         index = dic[preorder[pre_l]]
         size_l = index - ino_l
         root.left = buildChildTree(pre_l + 1, pre_l + size_l, ino_l, ino_l + size_l - 1)
         root.right = buildChildTree(pre_l + 1 + size_l, pre_r, ino_l + size_l + 1, ino_r)
     return root
Ejemplo n.º 3
0
    def recurseMerge(node1: TreeNode, node2: TreeNode) -> None or TreeNode:
        if not node1:
            return node2
        if not node2:
            return node1

        result = TreeNode(node1.val + node2.val)
        result.left = recurseMerge(node1.left, node2.left)
        result.right = recurseMerge(node1.right, node2.right)
        return result
Ejemplo n.º 4
0
 def constructChild(the_num: List[int]) -> TreeNode or None:
     if the_num:
         index = 0
         for indexes in range(0, len(the_num)):
             if the_num[indexes] > the_num[index]:
                 index = indexes
         result = TreeNode(the_num[index])
         result.left = constructChild(the_num[:index])
         result.right = constructChild(the_num[index + 1:])
         return result
 def constructChild(left_index: int, right_index: int) -> TreeNode or None:
     if left_index != right_index:
         index = cur = left_index
         while cur < right_index:
             if nums[cur] > nums[index]:
                 index = cur
             cur += 1
         result = TreeNode(nums[index])
         result.left = constructChild(left_index, index)
         result.right = constructChild(index + 1, right_index)
         return result
Ejemplo n.º 6
0
 def recursion(pre: List[int], ino: List[int]) -> TreeNode or None:
     root = None
     if pre:
         root = TreeNode(pre[0])
         index = 0
         #  每次都线性查找
         while index <= len(ino) - 1:
             if ino[index] != pre[0]:
                 index += 1
             else:
                 break
         root.left = recursion(pre[1:1 + index], ino[:index])
         root.right = recursion(pre[1 + index:], ino[index + 1:])
     return root
def constructMaximumBinaryTree(nums: List[int]) -> TreeNode or None:
    if nums:
        nodes = []
        for num in nums:
            cur = TreeNode(num)
            if not nodes or cur.val <= nodes[-1].val:
                nodes.append(cur)
                continue
            while cur.val > nodes[-1].val:
                child = nodes.pop()
                if not nodes or nodes[-1].val > cur.val:
                    cur.left = child
                else:
                    nodes[-1].right = child
                if not nodes:
                    break
            nodes.append(cur)
        while len(nodes) > 1:
            child = nodes.pop()
            nodes[-1].right = child
        return nodes[0]
Ejemplo n.º 8
0
 def recurseMerge(nodes: List[TreeNode]) -> None or TreeNode:
     if not nodes[0] and not nodes[1]:
         return
     result = TreeNode()
     left = []
     right = []
     if nodes[0]:
         result.val += nodes[0].val
         left.append(nodes[0].left)
         right.append(nodes[0].right)
     else:
         left.append(None)
         right.append(None)
     if nodes[1]:
         result.val += nodes[1].val
         left.append(nodes[1].left)
         right.append(nodes[1].right)
     else:
         left.append(None)
         right.append(None)
     result.left = recurseMerge(left)
     result.right = recurseMerge(right)
     return result
Ejemplo n.º 9
0
def pathSum(root: TreeNode, summary: int) -> List[List[int]]:
    def childrenSum(pointer: TreeNode, cur_sum: int,
                    cur_path: List[int]) -> List[List[int]]:
        res = []
        if pointer:
            cur = cur_path + [pointer.val]
            #  必须是叶子节点(左右子树为空)
            if cur_sum + pointer.val == summary and not pointer.left and not pointer.right:
                res.append(cur)

            cur_sum += pointer.val
            if pointer.left:
                res += childrenSum(pointer.left, cur_sum, cur)
            if pointer.right:
                res += childrenSum(pointer.right, cur_sum, cur)
        return res

    return childrenSum(root, 0, [])


if __name__ == "__main__":
    test = TreeNode(1, TreeNode(1, TreeNode(1), TreeNode(1)),
                    TreeNode(1, TreeNode(1), TreeNode(1)))
    print(pathSum(test, 3))
    test2 = TreeNode(1, TreeNode(2))
    print(pathSum(test2, 1))
    test3 = TreeNode(1)
    print(pathSum(test3, 1))
    test4 = TreeNode(-2, None, TreeNode(-3))
    print(pathSum(test4, -5))
Ejemplo n.º 10
0
    result = []
    if root:
        node_list = [root]
        visited = [0]
        while node_list:
            if visited[0] == 0:
                visited[0] = 1
                index = 0
                if node_list[index].left:
                    node_list.insert(0, node_list[index].left)
                    visited.insert(0, 0)
                    index = 1
                if node_list[index].right:
                    if index == 0:
                        node_list.insert(1, node_list[index].right)
                        visited.insert(1, 0)
                    else:
                        node_list.insert(2, node_list[index].right)
                        visited.insert(2, 0)
            else:
                result.append(node_list[0].val)
                node_list.pop(0)
                visited.pop(0)
    return result


if __name__ == "__main__":
    test = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)),
                    TreeNode(3, TreeNode(6), TreeNode(7)))
    print(postorderTraversal(test))  # [4,2,5,1,6,3,7]
Ejemplo n.º 11
0
        if not nodes[0] and not nodes[1]:
            return
        result = TreeNode()
        left = []
        right = []
        if nodes[0]:
            result.val += nodes[0].val
            left.append(nodes[0].left)
            right.append(nodes[0].right)
        else:
            left.append(None)
            right.append(None)
        if nodes[1]:
            result.val += nodes[1].val
            left.append(nodes[1].left)
            right.append(nodes[1].right)
        else:
            left.append(None)
            right.append(None)
        result.left = recurseMerge(left)
        result.right = recurseMerge(right)
        return result

    return recurseMerge([t1, t2])


if __name__ == "__main__":
    tree1 = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4)))
    tree2 = TreeNode(1, TreeNode(2), TreeNode(3))
    print(mergeTrees(tree1, tree2))
Ejemplo n.º 12
0
from collections import deque

from typing import List


def largestValues(root: TreeNode) -> List[int]:
    res = []
    if root:
        node_list = deque([[root, 1]])
        layers = 0
        while node_list:
            if node_list[0][0].left:
                node_list.append([node_list[0][0].left, node_list[0][1] + 1])
            if node_list[0][0].right:
                node_list.append([node_list[0][0].right, node_list[0][1] + 1])
            if node_list[0][1] > layers:
                layers = node_list[0][1]
                res.append(node_list[0][0].val)
            else:
                if res[-1] < node_list[0][0].val:
                    res[-1] = node_list[0][0].val
            node_list.popleft()
    return res


if __name__ == "__main__":
    test = TreeNode(1, TreeNode(3, TreeNode(5), TreeNode(3)),
                    TreeNode(2, None, TreeNode(9)))
    print(largestValues(test))
Ejemplo n.º 13
0
   15   7

返回它的最大深度 3
"""

# Definition for singly-linked list.
from DSAA.data_structure.basic.LeetcodeNode import TreeNode


def maxDepth(root: TreeNode or None) -> int:
    def recursion(pointer: TreeNode) -> int:
        left = right = 0
        if pointer:
            if pointer.left:
                left = recursion(pointer.left)
            if pointer.right:
                right = recursion(pointer.right)
            return 1 + max(left, right)
        return 0
    return recursion(root)


if __name__ == "__main__":
    test = TreeNode(1, TreeNode(4), TreeNode(3))
    print(maxDepth(test))  # 2
    test2 = TreeNode(1, TreeNode(2, TreeNode(8, None, TreeNode(5))), TreeNode(3))
    print(maxDepth(test2))  # 4
    print(maxDepth(None))  # 0
    test3 = TreeNode(6)
    print(maxDepth(test3))  # 1
Ejemplo n.º 14
0
返回它的最小深度  2
"""

# Definition for a binary tree node.
from DSAA.data_structure.basic.LeetcodeNode import TreeNode


def minDepth(root: TreeNode) -> int:
    def childrenDepth(pointer: TreeNode) -> int:
        if pointer:
            left = right = 0
            if pointer.left:
                left = childrenDepth(pointer.left)
            if pointer.right:
                right = childrenDepth(pointer.right)
            if left == 0 or right == 0:
                return 1 + max(left, right)
            else:
                return 1 + min(left, right)
        return 0

    return childrenDepth(root)


if __name__ == "__main__":
    test = TreeNode(1, TreeNode(2))
    print(minDepth(test))  # 2
    test2 = TreeNode(1, TreeNode(2, TreeNode(4)),
                     TreeNode(3, None, TreeNode(5)))
    print(minDepth(test2))  # 3
Ejemplo n.º 15
0
    def isLeafNode(pointer: TreeNode) -> bool:
        if not pointer:
            return False
        if not pointer.left and not pointer.right:
            return True
        else:
            return False

    if not root:
        return False
    else:
        sum_list = []
        node_list = [root]
        node_list += pasteChildren(root)
    while node_list:
        if node_list[0]:
            node_list += pasteChildren(node_list[0])
        if isLeafNode(node_list[0]):
            sum_list.append(node_list[0].val)
        node_list.pop(0)
    dic = set(sum_list)
    if summary in dic:
        return True
    else:
        return False


if __name__ == "__main__":
    test = TreeNode(1, TreeNode(2, TreeNode(5, None, TreeNode(4))), TreeNode(3, TreeNode(2), None))
    print(hasPathSum(test, 6))
Ejemplo n.º 16
0
"""

# Definition for singly-linked list.
from DSAA.data_structure.basic.LeetcodeNode import TreeNode


def maxDepth(root: TreeNode or None) -> int:
    def recursion(pointer: TreeNode) -> int:
        this = 0
        left = right = 0
        if pointer:
            this = 1
            if pointer.left:
                left = recursion(pointer.left)
            if pointer.right:
                right = recursion(pointer.right)
        return this + max(left, right)

    return recursion(root)


if __name__ == "__main__":
    test = TreeNode(1, TreeNode(2), TreeNode(3))
    print(maxDepth(test))  # 2
    test2 = TreeNode(1, TreeNode(2, TreeNode(4, None, TreeNode(5))),
                     TreeNode(3))
    print(maxDepth(test2))  # 4
    print(maxDepth(None))  # 0
    test3 = TreeNode(5)
    print(maxDepth(test3))  # 1
Ejemplo n.º 17
0
    def returnChildren(pointer: TreeNode) -> List[TreeNode]:
        if not pointer:
            return []
        else:
            result = []
            if pointer.left:
                result.append(pointer.left)
            # else:
            #     result.append(None)
            if pointer.right:
                result.append(pointer.right)
            # else:
            #     result.append(None)
        return result

    count = 0
    node_list = [root]
    while node_list:
        node_pointer = node_list[0]
        node_list += returnChildren(node_pointer)
        if node_pointer:
            count += 1
        node_list.pop(0)
    return count


if __name__ == "__main__":
    tree = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)),
                    TreeNode(3, TreeNode(6)))
    print(countNodes(tree))
Ejemplo n.º 18
0
# Definition for a binary tree node.
from DSAA.data_structure.basic.LeetcodeNode import TreeNode


def findTilt(root: TreeNode or None) -> int:
    def traverse(pointer: TreeNode) -> List[int]:
        lefts = rights = 0
        tilt = val = 0
        if pointer:
            val = pointer.val
            if pointer.left:
                left_res = traverse(pointer.left)
                tilt += left_res[0]
                lefts += left_res[1]
            if pointer.right:
                right_res = traverse(pointer.right)
                tilt += right_res[0]
                rights += right_res[1]
        tilt += abs(lefts - rights)
        return [tilt, lefts + rights + val]

    return traverse(root)[0]


if __name__ == "__main__":
    test = TreeNode(1)
    print(findTilt(test))
    test3 = TreeNode(1, TreeNode(2, TreeNode(8)), TreeNode(3))
    print(findTilt(test3))
Ejemplo n.º 19
0
9   6 3   1
"""

# Definition for a binary tree node.
from DSAA.data_structure.basic.LeetcodeNode import TreeNode


def invertTree(root: TreeNode) -> TreeNode:
    def returnChildren(pointer: TreeNode):
        result = []
        if pointer:
            if pointer.left:
                result.append(pointer.left)
            if pointer.right:
                result.append(pointer.right)
        return result

    if root:
        node_list = [root]
        while node_list:
            node_list += returnChildren(node_list[0])
            node_list[0].left, node_list[0].right = node_list[
                0].right, node_list[0].left
            node_list.pop(0)
    return root


if __name__ == "__main__":
    test = TreeNode(1)
    print(invertTree(test))
Ejemplo n.º 20
0
"""

# Definition for a binary tree node.
from DSAA.data_structure.basic.LeetcodeNode import TreeNode

from typing import List


def largestValues(root: TreeNode) -> List[int]:
    res = []

    def recursion(node: TreeNode, layers: int) -> None:
        if node:
            if len(res) < layers:
                res.append(node.val)
            else:
                res[layers - 1] = max(res[layers - 1], node.val)
            if node.left:
                recursion(node.left, layers + 1)
            if node.right:
                recursion(node.right, layers + 1)

    recursion(root, 1)
    return res


if __name__ == "__main__":
    test = TreeNode(0, TreeNode(-1))
    print(largestValues(test))
Ejemplo n.º 21
0
from DSAA.data_structure.basic.LeetcodeNode import TreeNode
from Leetcode.isSubtree_572.isSubtree2 import isSubtree

if __name__ == "__main__":
    test2 = TreeNode(1, TreeNode(1, TreeNode(1, TreeNode(1, TreeNode(1, None, TreeNode(2))))))
    test1 = TreeNode(1, TreeNode(1, TreeNode(1, TreeNode(1, TreeNode(1, test2)))))
    print(isSubtree(test1, test2))  # True
    test3 = TreeNode(1, None, TreeNode(1, None, TreeNode(1, None, TreeNode(1, TreeNode(2)))))
    test4 = TreeNode(1, None, TreeNode(1, None, TreeNode(1, None, TreeNode(1, None, test3))))
    print(isSubtree(test3, test4))  # False
    test5 = TreeNode(-6, TreeNode(-9, None, TreeNode(-8, None, TreeNode(-7))), TreeNode(-3, TreeNode(-4), TreeNode(1, TreeNode(0), TreeNode(5, TreeNode(2)))))
    test6 = TreeNode(-6, TreeNode(-9, None, TreeNode(-8, None, TreeNode(-7))), TreeNode(-3, TreeNode(-4), TreeNode(1)))
    print(isSubtree(test5, test6))  # False
Ejemplo n.º 22
0
"""

import collections

# Definition for a binary tree node.
from DSAA.data_structure.basic.LeetcodeNode import TreeNode

from typing import List


def pathSum(root: TreeNode, summary: int) -> List[List[int]]:
    res = []
    if root:
        node_list = collections.deque([[root, [root.val], root.val]])
        while node_list:
            tmp = node_list.popleft()
            node, path, cur_sum = tmp[0], tmp[1], tmp[2]
            if not node.left and not node.right and cur_sum == summary:
                res.append(path)
            if node.left:
                node_list.append([node.left, path + [node.left.val], cur_sum + node.left.val])
            if node.right:
                node_list.append([node.right, path + [node.right.val], cur_sum + node.right.val])

    return res


if __name__ == "__main__":
    test = TreeNode(1, TreeNode(1, TreeNode(1), TreeNode(1)), TreeNode(1, TreeNode(1), TreeNode(1)))
    print(pathSum(test, 3))