Exemplo n.º 1
0
    def recoverFromPreorder(self, S: str) -> TreeNode:
        # 根节点的值
        val, begin = transform(S, 0)
        # 建树
        root = TreeNode(val)
        stack = deque()
        stack.append(root)
        # 循环至字符串结尾
        while begin < len(S):
            # 当前节点的深度,并更新下标
            dep, begin = depth(S, begin)
            # 当前节点的值,并更新下标
            val, begin = transform(S, begin)
            # 如果深度小于栈里的元素个数,出栈至深度等于栈里的元素个数
            if dep < len(stack):
                while dep < len(stack):
                    stack.pop()

                node = TreeNode(val)
                # 将其加到栈顶的右子节点上
                stack[-1].right = node
                # 入栈
                stack.append(node)

            # 如果深度等于栈里的元素个数
            else:
                # 临时节点加到栈顶的左子节点上,并入栈
                node = TreeNode(val)
                stack[-1].left = node
                stack.append(node)

        return stack[0]
Exemplo n.º 2
0
 def invertTree(self, root: TreeNode) -> TreeNode:
     if root:
         # 保存右节点的信息
         right = root.right
         # 右节点递归翻转
         root.right = self.invertTree(root.left)
         # 左节点递归翻转
         root.left = self.invertTree(right)
         return root
     else:
         return None
Exemplo n.º 3
0
    def buildTree(self, inorder: [int], postorder: [int]) -> TreeNode:
        """
        Solution:
        1. 如果 inorder 列表为空,返回 None
        2. 如果 inorder 长度为 1,直接返回
        3. 由 postorder[-1] 拿到根节点
        4. 找到根节点在 inorder[] 中的位置
        5. 根据 inorder 和 postorder 列表等长的特性
            1. 递归左子树
            2. 赌鬼右子树

        :param inorder:
        :param postorder:
        :return:
        """

        if not inorder:
            return None

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

        root = TreeNode(postorder[-1])
        sep = inorder.index(postorder[-1])
        if sep == 0:
            root.right = self.buildTree(inorder[1:], postorder[:-1])
        elif sep == len(inorder) - 1:
            root.left = self.buildTree(inorder[:-1], postorder[:-1])
        else:
            root.left = self.buildTree(inorder[:sep], postorder[:sep])
            root.right = self.buildTree(inorder[(sep + 1):], postorder[sep:-1])
        return root
Exemplo n.º 4
0
def mergeTree2(t1: TreeNode, t2: TreeNode):
    if not t1 and not t2:
        return
    if not t1:
        t1 = t2
        return
    if not t2:
        return
    t1.val += t2.val
    if t1.left and t2.left:
        mergeTree2(t1.left, t2.left)
    elif t2.left:
        t1.left = t2.left

    if t1.right and t2.right:
        mergeTree2(t1.right, t2.right)
    elif t2.right:
        t1.right = t2.right
Exemplo n.º 5
0
 def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
     if not root:
         return TreeNode(val)
     node = root
     while node:
         # 小于当前节点的值,往左子树找
         if val < node.val:
             # 左子树不空,往左子树找
             if node.left:
                 node = node.left
             else:
                 node.left = TreeNode(val)
                 return root
         # 大于当前节点的值,往右子树找
         else:
             # 右子树不空,往右子树找
             if node.right:
                 node = node.right
             else:
                 node.right = TreeNode(val)
                 return root
     return root
from LeetCode.TreeNode import TreeNode


class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root:
            return

        # 当根节点的值在两个值之间时,根节点一定为两节点的最近公共祖先
        if p.val <= root.val <= q.val or q.val <= root.val <= p.val:
            return root

        # 当两个节点的值都比根节点值小时,递归到其左子树
        if p.val < root.val and q.val < root.val:
            return self.lowestCommonAncestor(root.left, p, q)
        # 否则,两个节点的值肯定都比根节点值大,递归到其右子树
        else:
            return self.lowestCommonAncestor(root.right, p, q)


root = TreeNode(-1).list2Tree([6, 2, 8, 0, 4, 7, 9, 'null', 'null', 3, 5])
p = TreeNode(2)
q = TreeNode(4)

print(Solution().lowestCommonAncestor(root, p, q).val)
Exemplo n.º 7
0
from LeetCode.TreeNode import TreeNode


class Solution:
    def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
        if not root:
            return TreeNode(val)
        node = root
        while node:
            # 小于当前节点的值,往左子树找
            if val < node.val:
                # 左子树不空,往左子树找
                if node.left:
                    node = node.left
                else:
                    node.left = TreeNode(val)
                    return root
            # 大于当前节点的值,往右子树找
            else:
                # 右子树不空,往右子树找
                if node.right:
                    node = node.right
                else:
                    node.right = TreeNode(val)
                    return root
        return root


root = TreeNode(-1).list2Tree([4, 2, 7, 1, 3])
Solution().insertIntoBST(root, 5).print_tree()
Exemplo n.º 8
0

def inOrderTraverse(val, node: TreeNode) -> bool:
    if node.left:
        if not inOrderTraverse(val, node.left):
            return False

    if not val:
        val.append(node.val)
    elif val[0] < node.val:
        val[0] = node.val
    else:
        return False

    if node.right:
        if not inOrderTraverse(val, node.right):
            return False

    return True


# l = [5, 1, 4, 'null', 'null', 3, 6]
# tree = TreeNode(-1).list2Tree(l)
# print(isValidBST(tree))
#
# print(isValidBST(TreeNode(-1).list2Tree([0])))
# print(isValidBST(TreeNode(-1).list2Tree([0, -1, 'null'])))
# print(isValidBST(TreeNode(-1).list2Tree([2, 1, 3])))
# print(isValidBST(TreeNode(-1).list2Tree([1, 1])))
print(isValidBST(TreeNode(-1).list2Tree([0, 'null', -1])))
            if ls_max > 0:
                p_max = p_max + ls_max
            if rs_max > 0:
                p_max = p_max + rs_max

            # MAX_PATH[0] 更新为 MAX_PATH[0] 与 双边路径较大者
            MAX_PATH[0] = max(MAX_PATH[0], p_max)

            # 单边路径存在非负数 更新单边路径最大和
            if ls_max > 0 or rs_max > 0:
                ps_max = ps_max + max(ls_max, rs_max)

            return ps_max
        else:
            # 空节点的值0,MAX_PATH 也不更新
            return 0


t = TreeNode(-1).list2Tree([-10, 9, 20, 'null', 'null', 15, 7])
print(Solution().maxPathSum(t))

t = TreeNode(-1).list2Tree([-10, 18, 20, 'null', 'null', 15, 7])
print(Solution().maxPathSum(t))

t = TreeNode(-1).list2Tree([8, -10, 6, 6, 5, 3, -1])
print(Solution().maxPathSum(t))

t = TreeNode(-1).list2Tree(
    [9, 6, -3, 'null', 'null', -6, 2, 'null', 'null', 2, 'null', -6, -6, -6])
print(Solution().maxPathSum(t))
def serialize_tree(s: TreeNode, res: [str]):
    if not s:
        res.append('#')
    else:
        res.append(str(s.val))

    if s.left:
        serialize_tree(s.left, res)
    else:
        res.append('#')
    if s.right:
        serialize_tree(s.right, res)
    else:
        res.append('#')


# test kmp algorithm
# str1 = 'absniasniajs'
# str2 = 'sniasnia'
# print(kmp(str1, str2))

# test case 1
# s = TreeNode(-1).list2Tree([3,4,5,1,2,'null','null','null','null',0])
# t = TreeNode(-1).list2Tree([4,1,2])
# print(isSubtree(s, t))

# test case 2
s = TreeNode(-1).list2Tree([12])
t = TreeNode(-1).list2Tree([2])
print(isSubtree(s, t))
Exemplo n.º 11
0
from LeetCode.TreeNode import TreeNode


class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if root:
            # 保存右节点的信息
            right = root.right
            # 右节点递归翻转
            root.right = self.invertTree(root.left)
            # 左节点递归翻转
            root.left = self.invertTree(right)
            return root
        else:
            return None


Solution().invertTree(TreeNode(-1).list2Tree([1, 'null', 2])).print_tree()
from LeetCode.TreeNode import TreeNode
from collections import deque


def levelOrderBottom(root: TreeNode) -> [[int]]:
    if not root:
        return []
    queue = deque()
    queue.append(root)
    result = []
    while queue:
        tmp = []
        k = len(queue)
        while k > 0:
            node = queue.popleft()
            tmp.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
            k = k - 1

        result.append(tmp)

    return result[::-1]


tree = TreeNode(-1).list2Tree([3, 9, 20, "null", "null", 15, 7])
print(levelOrderBottom(tree))
Exemplo n.º 13
0
class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> [[int]]:
        """
        Solution:
            深度优先遍历。
            记录路径和,如果 sum == root.val 且当前 root 为叶子节点,将路径添加至总集合

        :param root:
        :param sum:
        :return:
        """
        if not root:
            return []
        res = []

        def pathSum2(root, sum, path):
            tmp = [*path, root.val]
            if sum == root.val and not root.left and not root.right:
                res.append(tmp)
            if root.left:
                pathSum2(root.left, sum - root.val, tmp)
            if root.right:
                pathSum2(root.right, sum - root.val, tmp)

        pathSum2(root, sum, [])
        return res


tree = TreeNode(-1).list2Tree([5, 4, 8, 11, 13, 4, 'null', 7, 2, 'null', 'null', 5, 1])
print(*Solution().pathSum(tree, 22), sep='\n')
Exemplo n.º 14
0
        利用层次遍历的方法,每次取出当前层所有节点,做值的累加和
        对于当前层的每个节点,如果存在子节点(左子或右子),将其加入队列
        当下一层节点为空时,表明当前是最后一层节点,将累加和输出即可

    :param root:
    :return:
    """
    if not root:
        return 0
    queue = deque()
    queue.append(root)
    while queue:
        # 上一层的节点数
        num = len(queue)
        sum = 0
        while num != 0:
            node = queue.popleft()
            sum = sum + node.val
            num = num - 1
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        if len(queue) == 0:
            return sum

    return 0


print(deepSum(TreeNode(-1).list2Tree([1, 2, 3, 4, 5, 'null', 7])))
from LeetCode.TreeNode import TreeNode


def convertBST(root: TreeNode) -> TreeNode:
    """
    遍历顺序为:右->中->左
    或称为反中序遍历

    :param root:
    :return:
    """
    sumOfRight, stack = 0, []
    node = root
    while stack or node:
        if node:
            stack.append(node)
            node = node.right
        else:
            node = stack.pop(-1)
            node.val += sumOfRight
            sumOfRight = node.val
            node = node.left

    return root


convertBST(TreeNode(-1).list2Tree([5, 2, 13])).print_tree()
Exemplo n.º 16
0
            return t2
        mergeTree2(t1, t2)
        return t1


def mergeTree2(t1: TreeNode, t2: TreeNode):
    if not t1 and not t2:
        return
    if not t1:
        t1 = t2
        return
    if not t2:
        return
    t1.val += t2.val
    if t1.left and t2.left:
        mergeTree2(t1.left, t2.left)
    elif t2.left:
        t1.left = t2.left

    if t1.right and t2.right:
        mergeTree2(t1.right, t2.right)
    elif t2.right:
        t1.right = t2.right


# t1 = TreeNode(-1).list2Tree([1, 3, 2, 5])
# t2 = TreeNode(-1).list2Tree([2, 1, 3, 'null', 4, 'null', 7])
# t1 = TreeNode(-1).list2Tree([])
t2 = TreeNode(-1).list2Tree([1])
Solution().mergeTrees(None, t2).print_tree()
Exemplo n.º 17
0
from collections import deque

from LeetCode.TreeNode import TreeNode


def inorderTraversal(root: TreeNode) -> [int]:
    res, stack = [], deque()
    node = root
    while node or stack:
        if node:
            stack.append(node)
            node = node.left
        else:
            node = stack.pop()
            res.append(node.val)
            node = node.right

    return res


print(inorderTraversal(TreeNode(-1).list2Tree([1, 'null', 2, 3])))
Exemplo n.º 18
0
        # 存放结果
        res = []
        # 从左往右遍历时flag为true,从右往左时为false
        flag = True
        while queue:
            num_of_node = len(queue)
            cur = []
            while num_of_node > 0:
                node = queue.popleft()
                cur.append(node.val)

                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)

                num_of_node = num_of_node - 1

            if flag:
                res.append(cur)
                flag = False
            else:
                res.append(cur[::-1])
                flag = True

        return res


tree = TreeNode(-1).list2Tree([3, 9, 20, 'null', 'null', 15, 7])
print(Solution().zigzagLevelOrder(tree))
        tmp_times = tmp_value = -2
        stack = []
        node = root
        while stack or node:
            if node:
                stack.append(node)
                node = node.left
            else:
                node = stack.pop(-1)
                if node.val != tmp_value:
                    if tmp_times > common_times:
                        res = [tmp_value]
                        common_times = tmp_times
                    elif tmp_times == common_times:
                        res.append(tmp_value)
                    tmp_value = node.val
                    tmp_times = 1
                else:
                    tmp_times += 1
                node = node.right

        if tmp_times > common_times:
            res = [tmp_value]
        elif tmp_times == common_times:
            res.append(tmp_value)

        return res


print(Solution().findMode(TreeNode(-1).list2Tree([1, 'null', 2, 2])))