예제 #1
0
파일: main.py 프로젝트: hasadent/leetcode
def test(inpList, ansList):
    root = TreeNode.fromList(inpList)
    ans = TreeNode.fromList(ansList)

    s = Solution()
    s.recoverTree(root)
    if root != ans:
        print('mine')
        root.printTree()
        print('answer')
        ans.printTree()
예제 #2
0
def test(treeList, ans_0, ans_1):

    root = TreeNode.fromList(treeList)

    s = Solution()
    r = s.maxDepth(root)
    ans = ans_0

    if r != ans:
        print('maxDepth: not correct', 'output:', r, 'excpeted:', ans)
        root.printTree()

    r = s.minDepth(root)
    ans = ans_1
    if r != ans:
        print('minDepth: not correct', 'output:', r, 'excpeted:', ans)
        root.printTree()
예제 #3
0
파일: main.py 프로젝트: hasadent/leetcode

class Solution:
    def constructFromPrePost(self, pre: List[int],
                             post: List[int]) -> TreeNode:
        if not pre or not post:
            return None

        node = TreeNode(pre[0])
        if len(pre) != 1:
            x = post.index(pre[1]) + 1
            node.left = self.constructFromPrePost(pre[1:x + 1], post[0:x])
            node.right = self.constructFromPrePost(pre[x + 1:], post[x:-1])

        return node


def test(pre, post, ans):
    s = Solution()
    r = s.constructFromPrePost(pre, post)
    if r != ans:
        print('mine')
        r.printTree(1)
        print('ans')
        ans.printTree(1)
        print(ans)


test([1, 2, 4, 5, 3, 6, 7], [4, 5, 2, 6, 7, 3, 1],
     TreeNode.fromList([1, 2, 3, 4, 5, 6, 7]))
예제 #4
0
파일: main.py 프로젝트: hasadent/leetcode
import sys
sys.path.append('../common')
from TreeNode import TreeNode
from typing import List


class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        if not inorder:
            return None

        v = postorder.pop()
        x = inorder.index(v)
        r = self.buildTree(inorder[x + 1:], postorder)
        l = self.buildTree(inorder[0:x], postorder)
        return TreeNode(v, l, r)


def test(preorder, inorder, ans):
    s = Solution()
    r = s.buildTree(preorder, inorder)
    if r != ans:
        print('mine')
        r.printTree(1)
        print('ans')
        ans.printTree(1)


test([9, 3, 15, 20, 7], [9, 15, 7, 20, 3],
     TreeNode.fromList([3, 9, 20, None, None, 15, 7]))
예제 #5
0
            v, i = data[i], i + 1
            if v != None:
                n.left = TreeNode(v)
                queue.append(n.left)

            if i < len(data):
                v, i = data[i], i + 1
                if v != None:
                    n.right = TreeNode(v)
                    queue.append(n.right)

        return root


def test(root):
    codec = Codec()

    print('input')
    root.printTree(4)

    r0 = codec.serialize(root)
    print('serialize', r0)
    r1 = codec.deserialize(r0)
    print('deserialize')
    r1.printTree(4)


test(TreeNode.fromList([1, 2, 3, None, None, 4, 5]))

test(TreeNode.fromList([-1, 0, 1]))