Exemplo n.º 1
0
        if not root:
            return []
        # 然后是简单情况,可以作为递归终止条件
        # 如果左右为空即为叶子节点且值为目标值,那么直接返回答案
        if not root.right and not root.left and root.val == target:
            return [[root.val]]

        ans = []
        # 如果存在左子树
        if root.left:
            # 对于左子树返回的每个元素(是一个列表),加上这个节点值,则可以构成完整路径
            for item in self.FindPath(root.left, target - root.val):
                # 叶子节点给返回结果才加,不然不加入ans
                if len(item):
                    ans.append([root.val] + item)
        # 同上
        if root.right:
            for item in self.FindPath(root.right, target - root.val):
                if len(item):
                    ans.append([root.val] + item)
        return ans


if __name__ == '__main__':
    my_tree = maketree([10, 5, 4, 7, 12], [4, 5, 7, 10, 12])
    target = 22
    s = Solution()

    answer = s.FindPath(my_tree, target)
    print(answer)
Exemplo n.º 2
0
    def next(self) -> int:
        """
        @return the next smallest number
        """
        while self.stack:
            node, flag = self.stack.pop()
            if flag:
                return node.val
            else:
                if node.right:
                    self.stack.append((node.right, False))
                self.stack.append((node, True))
                if node.left:
                    self.stack.append((node.left, False))

    def hasNext(self) -> bool:
        """
        @return whether we have a next smallest number
        """
        return self.stack != []


if __name__ == '__main__':
    tree = maketree([4, 2, 1, 3, 6, 5, 7],
                    [1, 2, 3, 4, 5, 6, 7])  # [1, 3, 2, 5, 7, 6, 4]
    s = BSTIterator(tree)
    while s.hasNext():
        print(s.next())
    print("over")
Exemplo n.º 3
0
# 根据概念最简单的递归,但是时间效率必然很差
def helper(root: TreeNode):
    if not root:
        return 0
    if not root.left and not root.right:
        return 1
    left_part = helper(root.left)
    right_part = helper(root.right)
    if type(left_part) is not int or type(right_part) is not int:
        return False
    if abs(left_part - right_part) < 2:
        return max(left_part, right_part) + 1
    else:
        return False


class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        if helper(root) is False:
            return False
        return True


if __name__ == '__main__':
    from utils.maketree import maketree

    mytree = maketree([1, 2, 4, 6, 7, 5, 3], [6, 4, 7, 2, 5, 1, 3])
    s=Solution()
    ans=s.isBalanced(mytree)
    print(ans)
Exemplo n.º 4
0
# @Author  : frelikeff
# @Site    :
# @File    : 199answer.py
# @Software: PyCharm
from utils.maketree import TreeNode, maketree
from typing import List


class Solution:
    def rightSideView(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        ans = []
        deque = [root]
        while deque:
            ans.append(deque[-1].val)
            next_deque = []
            for node in deque:
                if node.left:
                    next_deque.append(node.left)
                if node.right:
                    next_deque.append(node.right)
            deque = next_deque
        return ans


if __name__ == '__main__':
    my_tree = maketree([1, 2, 5, 3, 4], [2, 5, 1, 3, 4])
    ans = Solution().rightSideView(my_tree)
    print(ans)
Exemplo n.º 5
0
            return
        if not root.left and not root.right:
            return
        elif not root.left:
            self.flatten(root.right)
        elif not root.right:
            self.flatten(root.left)
            root.right = root.left
            root.left = None
        else:
            self.flatten(root.left)
            self.flatten(root.right)
            memo = root.right
            root.right = root.left
            root.left = None
            while root.right:
                root = root.right

            root.right = memo

        return


if __name__ == '__main__':
    mytree = maketree([1, 2, 3, 4, 5, 6], [3, 2, 4, 1, 5, 6])
    s = Solution()
    s.flatten(mytree)
    while mytree:
        print(mytree.left, mytree.right.val)
        mytree = mytree.right
Exemplo n.º 6
0
def hasSubtree(s, t):
    flag = False
    if s and t:
        if s.val == t.val:
            flag = is_prefixtree(s.left, t.left) and is_prefixtree(s.right, t.right)
        if not flag:
            return hasSubtree(s.left, t) or hasSubtree(s.right, t)

    return flag

# 判断t 是不是 s的前缀树
def is_prefixtree(s, t):
    if not t:
        return True
    if not s:
        return False
    if s.val == t.val:
        return is_prefixtree(s.left, t.left) and is_prefixtree(s.right, t.right)
    return False


if __name__ == '__main__':
    from utils.maketree import maketree_complex as maketree

    t = maketree([8, 9, 3], [9, 8, 3])
    s = maketree([8, 8, 9, 2, 4, 7, 7], [9, 8, 4, 2, 7, 8, 7])
    a, b = t.left, t.right
    c, d = s.left.left, s.left.right
    ans = hasSubtree(s, t)
    print(ans)
    print(is_prefixtree(c, a), is_prefixtree(d, b))
Exemplo n.º 7
0
6 10
/\ /\
5 7 9 11
输出:
8
/ \
10 6
/\ /\
11 9 7 5
"""
from utils.maketree import maketree, TreeNode,LDRdg,DLRdg


class Solution:
    # 镜像对称转换
    def MirrorRecursively(self, root: TreeNode) -> TreeNode or None:
        if not root:
            return None

        root.left, root.right = self.MirrorRecursively(root.right), self.MirrorRecursively(
            root.left)
        return root


if __name__ == '__main__':
    s=Solution()
    my_tree = maketree([4, 2, 1, 3, 6, 5, 7], [1, 2, 3, 4, 5, 6, 7])
    ans = s.MirrorRecursively(my_tree)
    print(LDRdg(ans))
    print(DLRdg(ans))
Exemplo n.º 8
0
def helper(root: TreeNode):  # 需要返回两个值,一个是ans,一个是根节点到叶节点的最大值
    if not root.left and not root.right:
        return root.val, root.val
    elif not root.right:
        left_ans, left_top = helper(root.left)
        end = max(left_top + root.val, root.val)
        return max(left_ans, end), end
    elif not root.left:

        right_ans, right_top = helper(root.right)
        end = max(right_top + root.val, root.val)
        return max(right_ans, end), end
    else:
        left_ans, left_top = helper(root.left)
        right_ans, right_top = helper(root.right)
        end = max(left_top + root.val, root.val + right_top, root.val)
        return max(left_ans, right_ans, left_top + root.val + right_top,
                   end), end


class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        return helper(root)[0]


if __name__ == '__main__':
    s = Solution()
    mytree = maketree([1, 2, 3], [2, 1, 3])
    print(s.maxPathSum(mytree))
Exemplo n.º 9
0
        # 初始化ans列表,以及最开始要看的层
        ans = []
        level = [root]

        while level:  # 如果这层还有节点

            cur = []  # 这层的节点值列表,最终添加至ans
            next_level = []  # 这层节点的 左右子节点,也就是下一层
            for node in level:  # 对这层的所有节点进行遍历
                cur.append(node.val)  # 添加值

                # 如果左右存在,那么添加至下一层
                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)

            # 把这层遍历的值结果添加至ans
            # 遍历层置为下一层
            ans.append(cur)
            level = next_level
        return ans


if __name__ == '__main__':
    my_tree = maketree([1, 2, 4, 5, 8, 9, 3, 6, 7],
                       [4, 2, 8, 5, 9, 1, 6, 3, 7])
    s = Solution()
    answer = s.levelOrder(my_tree)
    print(answer)
Exemplo n.º 10
0
class Solution:
    # 将二叉树转换为有序双向链表
    def Convert(self, root):
        return convert_two(root)[0]

    # 获得链表的正向序和反向序
    def printList(self, head):
        while head.right:
            print(head.val, end=" ")
            head = head.right
        print(head.val)
        while head:
            print(head.val, end=" ")
            head = head.left


if __name__ == '__main__':
    s = Solution()
    preorder_seq = [4, 2, 1, 3, 6, 5, 7]
    middleorder_seq = [1, 2, 3, 4, 5, 6, 7]
    treeRoot1 = maketree(preorder_seq, middleorder_seq)
    head = s.Convert(treeRoot1)
    s.printList(head)

    #      4
    #    /   \
    #   2     6
    #  / \   / \
    # 1   3 5   7
Exemplo n.º 11
0
        stack = []
        stack.append(root)
        while stack:
            cur_node = stack.pop()
            if cur_node:
                cur_node.val = func[cur_node.val]
                stack.extend([cur_node.right, cur_node.left])
        return root


# 这个是真的屌 # TODO
class Solution2:
    def bstToGst(self, root: TreeNode) -> TreeNode:
        def postOrder(nd, acc=0) -> int:
            if not nd: return acc
            nd.val += postOrder(nd.right, acc)
            return postOrder(nd.left, nd.val)

        postOrder(root)
        return root


if __name__ == '__main__':
    s = Solution()
    my_tree = maketree([4, 1, 0, 2, 3, 6, 5, 7, 8], list(range(9)))
    print(BT_level_order_traversal(my_tree))
    ans = s.bstToGst(my_tree)

    print(BT_level_order_traversal(ans))