コード例 #1
0
    def test_binarytree_0001(self):
        tree = TreeNode.from_list([0, None, 2])

        assert tree.val == 0
        assert tree.left is None
        assert tree.right.val == 2
        assert tree.right == TreeNode(2)
コード例 #2
0
    def test_binarytree_0002(self):
        tree = TreeNode.from_list([1, None, 0, 0, 1], )

        assert tree.val == 1
        assert tree.left is None
        assert tree.right.val == 0
        assert tree.right.left == TreeNode(0)
        assert tree.right.right == TreeNode(1)
コード例 #3
0
    def test_binarytree_0004(self):
        tree = TreeNode.from_list([1, 2, None, 4, None, 5, 6], )

        assert tree.val == 1
        assert tree.left.val == 2
        assert tree.right is None
        assert tree.left.left.val == 4
        assert tree.left.right is None
        assert tree.left.left.left == TreeNode(5)
        assert tree.left.left.right == TreeNode(6)
コード例 #4
0
def main():

    list1 = [5, 2, 8, 1, 3, 7, 9]
    list2 = [4, 0, 6]

    tree1 = TreeNode.list2tree(list1)
    tree2 = TreeNode.list2tree(list2)

    result = get_two_trees_inorder(tree1, tree2)
    print(result)
コード例 #5
0
ファイル: sol1.py プロジェクト: wingkitlee0/leetcode_exercise
        def dfs(tree, val):
            if tree is None:
                pass

            if val < tree.val:
                if tree.left:
                    dfs(tree.left, val)
                else:
                    tree.left = TreeNode(val)
            if val > tree.val:
                if tree.right:
                    dfs(tree.right, val)
                else:
                    tree.right = TreeNode(val)
コード例 #6
0
 def test_to_list_middle_leaves(self):
     root = TreeNode(1)
     root.left = TreeNode(2)
     root.right = TreeNode(3)
     root.left.right = TreeNode(4)
     root.right.left = TreeNode(5)
     self.assertListEqual(to_list(root), [1, 2, 3, None, 4, 5])
コード例 #7
0
 def recur(root, left, right):
     if left > right: return  # 递归终止
     node = TreeNode(preorder[root])  # 建立根节点
     i = dic[preorder[root]]  # 划分根节点、左子树、右子树
     node.left = recur(root + 1, left, i - 1)  # 开启左子树递归
     node.right = recur(i - left + root + 1, i + 1, right)  # 开启右子树递归
     return node  # 回溯返回根节点
コード例 #8
0
 def deserialize(self, data):
     if data == "[]": return
     vals, i = data[1:-1].split(','), 1
     root = TreeNode(int(vals[0]))
     queue = collections.deque()
     queue.append(root)
     while queue:
         node = queue.popleft()
         if vals[i] != "null":
             node.left = TreeNode(int(vals[i]))
             queue.append(node.left)
         i += 1
         if vals[i] != "null":
             node.right = TreeNode(int(vals[i]))
             queue.append(node.right)
         i += 1
     return root
コード例 #9
0
    def insert(self, data):
        if not self.tree:
            self.tree = TreeNode(data)
            return

        p = self.tree
        while p != None:
            if data > p.val:
                if p.right == None:
                    p.right = TreeNode(data)
                    return
                p = p.right
            else:
                if p.left == None:
                    p.left = TreeNode(data)
                    return
                p = p.left
コード例 #10
0
        def dfs(lpre, rpre, lin, rin):
            #边界条件
            if lpre > rpre: return None
            if lpre == rpre:
                return TreeNode(preorder[lpre])

            #前序的第一个值是根节点
            root = TreeNode(preorder[lpre])
            #取出中序的根节点
            idx = dic[root.val]

            #递归左右子树
            leftTree = dfs(lpre + 1, lpre + (idx - lin), lin, idx - 1)
            rightTree = dfs(lpre + (idx - lin) + 1, rpre, idx + 1, rin)
            #连回根节点
            root.left = leftTree
            root.right = rightTree
            return root
コード例 #11
0
        def dfs(lpost, rpost, lin, rin):
            #边界条件
            if lpost > rpost: return None
            if lpost == rpost:
                return TreeNode(postorder[lpost])

            #后序的最后一个值是根节点
            root = TreeNode(postorder[rpost])
            #取出中序的根节点
            idx = dic[root.val]

            #递归左右子树
            leftTree = dfs(lpost, lpost + (idx - lin) - 1, lin, idx - 1)
            rightTree = dfs(lpost + (idx - lin), rpost - 1, idx + 1, rin)
            #连回根节点
            root.left = leftTree
            root.right = rightTree
            return root
コード例 #12
0
def main():

    root1 = [5,2,8,1,3,7,9]

    tree = TreeNode.list2tree(root1)

    # result = tree2list(tree)
    # print(result)

    dfs(tree)
コード例 #13
0
ファイル: common.py プロジェクト: MaHu6/LeetCode
def list2BinaryTree(root: TreeNode, nums: List, i: int):
    if i < len(nums):
        if nums[i] == None:  # 节点是空的时候 返回空
            return None
        else:
            root = TreeNode(nums[i])
            root.left = list2BinaryTree(root.left, nums, i * 2 + 1)
            root.right = list2BinaryTree(root.right, nums, i * 2 + 2)
        return root

    return root
コード例 #14
0
def main():
    input_list = [
        [5, 2, 8, 1, 3, 7, 9],
        [2, 1, 3],
    ]

    for lst in input_list:
        tree = TreeNode.list2tree(lst)

        result = get_inorder_iterative(tree)
        print(f"{lst} -> {result}")
コード例 #15
0
ファイル: sol2.py プロジェクト: wingkitlee0/leetcode_exercise
    def pruneTree(self, root: TreeNode) -> TreeNode:
        """
        prune the tree recursively!
        """

        if root is None:
            return None

        if root.left is not None:
            root.left = self.pruneTree(root.left)

        if root.right is not None:
            root.right = self.pruneTree(root.right)

        if root.left is None and root.right is None:
            if root.val == 0:
                return None
            else:
                return root

        return root
コード例 #16
0
ファイル: __init__.py プロジェクト: MaHu6/LeetCode
    def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:

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

        if not nums:
            return

        max_index = nums.index(max(nums))
        current_val = nums[max_index]
        current_node = TreeNode(current_val)

        left_nums = nums[:max_index]
        right_nums = nums[max_index + 1:]

        if left_nums:
            current_node.left = self.constructMaximumBinaryTree(left_nums)

        if right_nums:
            current_node.right = self.constructMaximumBinaryTree(right_nums)

        return current_node
コード例 #17
0
    def test_binarytree_0010(self):

        with pytest.raises(TypeError):
            TreeNode.from_list(None)

        assert TreeNode.from_list([]) is None
        assert TreeNode.from_list([None]) is None
        assert TreeNode.from_list([1]) == TreeNode(1)
コード例 #18
0
 def mergeTrees(self, t1, t2):
     """
     :type t1: TreeNode
     :type t2: TreeNode
     :rtype: TreeNode
     """
     # Write your code here
     if not t1 and not t2:
         return None
     elif t1 and t2:
         result = TreeNode(t1.value + t2.value)
         result.left = self.mergeTrees(t1.left, t2.left)
         result.right = self.mergeTrees(t1.right, t2.right)
         return result
     else:
         return t1 or t2
コード例 #19
0
        def helper(in_left, in_right):
            # 如果这里没有节点构造二叉树了,就结束
            if in_left > in_right:
                return None

            # 选择 post_idx 位置的元素作为当前子树根节点
            val = postorder.pop()
            root = TreeNode(val)

            # 根据 root 所在位置分成左右两棵子树
            index = idx_map[val]

            # 构造右子树
            root.right = helper(index + 1, in_right)
            # 构造左子树
            root.left = helper(in_left, index - 1)
            return root
コード例 #20
0
def listToTree(head):
    # We just simply append everything to the left node
    """
    Convert A sorted linkedlist into binary tree
    >>> lst = Node(1, Node(2, Node(3, Node(4))))
    >>> tree = listToTree(lst)
    >>> tmp = []
    >>> while tree is not None:
    ...     tmp.append(tree.data)
    ...     tree = tree.left
    >>> tmp
    [4, 3, 2, 1]
    """
    rst = None
    while head is not None:
        rst = TreeNode(head.data, rst, None)  # append to the left
        head = head.next
    return rst
コード例 #21
0
ファイル: __init__.py プロジェクト: MaHu6/LeetCode
def initNode() -> TreeNode:
    a = TreeNode(1)
    b = TreeNode(2)
    c = TreeNode(3)
    d = TreeNode(4)
    e = TreeNode(5)
    f = TreeNode(6)
    g = TreeNode(7)

    a.left = b
    a.right = c
    b.left = d
    b.right = e
    c.left = f
    c.right = g

    return a
コード例 #22
0
from binarytree import BinaryTree, TreeNode


def get_binary_tree_size(node):
    if node is None:
        return 0

    return 1 + get_binary_tree_size(node.left) + get_binary_tree_size(
        node.right)


if __name__ == "__main__":

    tree = BinaryTree(1)
    tree.root.left = TreeNode(2)
    tree.root.right = TreeNode(3)
    tree.root.left.left = TreeNode(4)
    tree.root.left.right = TreeNode(5)

    print(get_binary_tree_size(tree.root))
コード例 #23
0
 def test_to_list_value(self):
     root = TreeNode(1)
     self.assertListEqual(to_list(root), [1])
コード例 #24
0
 def test_to_list_both_children(self):
     root = TreeNode(1)
     root.left = TreeNode(2)
     root.right = TreeNode(3)
     self.assertListEqual(to_list(root), [1, 2, 3])
コード例 #25
0
 def test_to_list_missing_left(self):
     root = TreeNode(1)
     root.right = TreeNode(2) 
     self.assertListEqual(to_list(root), [1, None, 2])
コード例 #26
0
def test_1():
    sol = Solution()
    tree = TreeNode.list2tree([1, 2, 3])
    assert sol.findBottomLeftValue(tree) == 2
コード例 #27
0
"""解法2:递归
- 时间复杂度:O(N)。其中 N 为二叉树节点数;每循环一轮排除一层,二叉搜索树的层数最小为 logN (满二叉树),最大为 N(退化为链表)。
- 空间复杂度:O(N)。最差情况下,递归深度达到 N ,使用 O(N) 大小的额外空间。
"""
# class Solution:
#     def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
#         if root.val < p.val and root.val < q.val:
#             return self.lowestCommonAncestor(root.right, p, q)
#         if root.val > p.val and root.val > q.val:
#             return self.lowestCommonAncestor(root.left, p, q)
#         return root

if __name__ == "__main__":
    # root = [6,2,8,0,4,7,9,null,null,3,5]
    root = TreeNode(6)
    root.left = TreeNode(2)
    root.right = TreeNode(8)
    root.left.left = TreeNode(0)
    root.left.right = TreeNode(4)
    root.right.left = TreeNode(7)
    root.right.right = TreeNode(9)
    root.left.right.left = TreeNode(3)
    root.left.right.right = TreeNode(5)
    # p = 2
    p = root.left
    # q = 4
    q = root.left.right

    print(root)
    print(Solution().lowestCommonAncestor(root, p, q))  # 2
コード例 #28
0
ファイル: JZ26.py プロジェクト: Sibyl233/LeetCode
"""解法1:递归法
- 时间复杂度:O(MN)。其中 M,N 分别为树 A 和树 B 的节点数量。
- 空间复杂度:O(M)。
"""


class Solution:
    def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
        def recur(A, B):
            if not B: return True
            if not A or A.val != B.val: return False
            return recur(A.left, B.left) and recur(A.right, B.right)

        return bool(A and B) and (recur(A, B) or self.isSubStructure(
            A.left, B) or self.isSubStructure(A.right, B))


if __name__ == "__main__":
    A = TreeNode(3)
    A.left = TreeNode(4)
    A.right = TreeNode(5)
    A.left.left = TreeNode(1)
    A.left.right = TreeNode(2)

    B = TreeNode(4)
    B.left = TreeNode(1)

    print(A, B)

    print(Solution().isSubStructure(A, B))
コード例 #29
0
from binarytree import Node as TreeNode
from typing import List
import collections


class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root: return []
        res, queue = [], collections.deque()
        queue.append(root)
        while queue:
            tmp = []
            for _ in range(len(queue)):
                node = queue.popleft()
                tmp.append(node.val)
                if node.left: queue.append(node.left)
                if node.right: queue.append(node.right)
            res.append(tmp)
        return res


if __name__ == "__main__":
    root = TreeNode(3)
    root.left = TreeNode(9)
    root.right = TreeNode(20)
    root.right.left = TreeNode(15)
    root.right.right = TreeNode(7)
    print(root)
    print(Solution().levelOrder(root))
コード例 #30
0
ファイル: sol1.py プロジェクト: wingkitlee0/leetcode_exercise
    def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
        def dfs(tree, val):
            if tree is None:
                pass

            if val < tree.val:
                if tree.left:
                    dfs(tree.left, val)
                else:
                    tree.left = TreeNode(val)
            if val > tree.val:
                if tree.right:
                    dfs(tree.right, val)
                else:
                    tree.right = TreeNode(val)

        dfs(root, val)
        return root


if __name__ == '__main__':

    input_list = [(5, [4, 2, 7, 1, 3])]

    sol = Solution()

    for inp in input_list:
        tree = TreeNode.list2tree(inp[1])
        new_tree = sol.insertIntoBST(tree, inp[0])
        new_tree.printTree_bfs()