Example #1
0
 def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
     return TreeUtil.createTreeByPreInOrder(preorder, inorder)
Example #2
0
                indexBegin += 1
                indexEnd -= 1
        return True

    def isSymmetric_fast(self, root: TreeNode) -> bool:
        def equals(node1: TreeNode, node2: TreeNode):
            if not node1 and not node2:
                return True
            elif (node1 and node2) is None:
                return False
            return node1.val == node2.val and equals(
                node1.left, node2.right) and equals(node1.right, node2.left)

        if not root:
            return True
        return equals(root.left, root.right)


speedtest([Solution().isSymmetric,
           Solution().isSymmetric_fast], [
               TreeUtil.createTreeByPreInOrder(
                   [1, 2, 4, 6, 5, 7, 9, 10, 8, 3, 5, 8, 7, 9, 10, 4, 6],
                   [4, 6, 2, 7, 10, 9, 5, 8, 1, 8, 5, 9, 10, 7, 3, 6, 4])
           ])
speedtest([Solution().isSymmetric,
           Solution().isSymmetric_fast], [
               TreeUtil.createTreeByPreInOrder(
                   [1, 2, 4, 6, 5, 7, 9, 10, 8, 2, 5, 8, 7, 9, 10, 4, 6],
                   [4, 6, 2, 7, 10, 9, 5, 8, 1, 8, 5, 9, 10, 7, 2, 6, 4])
           ])
Example #3
0
                valIs = root.val
            else:
                nowLength += 1
            longest = max(longest, nowLength)
            detectLongestPath(root.left, valIs + 1, nowLength)
            detectLongestPath(root.right, valIs + 1, nowLength)

        longest = 0
        if not root:
            return 0
        detectLongestPath(root, root.val, 0)
        return longest


speedtest(
    [Solution().longestConsecutive,
     Solution().longestConsecutive_clumsy],
    [TreeUtil.createTreeByPreInOrder([1, 3, 2, 4, 5], [1, 2, 3, 4, 5])])
speedtest(
    [Solution().longestConsecutive,
     Solution().longestConsecutive_clumsy],
    [TreeUtil.createTreeByPreInOrder([2, 3, 2, 1], [2, 1, 2, 3])])
root = TreeNode(1)
node = root
for i in range(2, 5001):
    node.right = TreeNode(i)
    node = node.right
speedtest(
    [Solution().longestConsecutive,
     Solution().longestConsecutive_clumsy], [root])
import threading

from test_script import TreeNode, TreeUtil, timer


class Codec:
    def serialize(self, root: TreeNode) -> str:
        """
        Encodes a tree to a single string.
        """
        return str(TreeUtil.toValHeapToDict(root)).replace(' ', '')

    @timer
    def deserialize(self, data: str) -> TreeNode:
        """
        Decodes your encoded data to tree.
        """
        return TreeUtil.createTreeByHeapExpressedByDict(eval(data))


root = TreeUtil.createTreeByPreInOrder(list(range(1, 1001)), list(range(1, 1001)))
treeDictStr = Codec().serialize(root)
Codec().deserialize(treeDictStr)
print(treeDictStr)