Beispiel #1
0
from pytree import TreeNode


class Solution:
    def findTilt(self, root: TreeNode) -> int:
        def find(root):

            if root is None:
                return (0, 0)
            lo = find(root.left)
            ro = find(root.right)

            return (abs(lo[1] - ro[1]) + lo[0] + ro[0],
                    lo[1] + ro[1] + root.val)

        return find(root)[0]


root = '[1,2,3]'
root = '[4,2,9,3,5,null,7]'
root = '[21,7,14,1,1,2,2,3,3]'

root = TreeNode.fromStrList(root)
print(Solution().findTilt(root))
Beispiel #2
0
class Solution:
    def increasingBST(self, root: TreeNode) -> TreeNode:
        out = None
        pre = None

        def midorder(root):
            if root is None:
                return
            midorder(root.left)
            nonlocal pre
            root.left = None

            if pre is not None:
                pre.right = root
            else:
                nonlocal out
                out = root
            pre = root
            midorder(root.right)

        midorder(root)

        return out


inp = '[2,1,4,null,null,3]'
root = TreeNode.fromStrList(inp)
sl = Solution()
out = sl.increasingBST(root)
TreeNode.travel(out)
Beispiel #3
0
                while len(queue) > 0:
                    tmp = queue.popleft()

                    if tmp is None:
                        continue

                    if tmp.val % 2 == 0:
                        return False

                    if tmp.val <= prev:
                        return False
                    prev = tmp.val

                    if tmp.left is not None:
                        queue2.append(tmp.left)

                    if tmp.right is not None:
                        queue2.append(tmp.right)
            queue = queue2

        return True


root = '[1,10,4,3,null,7,9,12,8,6,null,null,2]'
root = '[5,4,2,3,3,7]'
root = '[5,9,1,3,5,7]'
root = '[1]'
root = '[11,8,6,1,3,9,11,30,20,18,16,12,10,4,2,17]'

print(Solution().isEvenOddTree(TreeNode.fromStrList(root)))
Beispiel #4
0
            if r1.val != r2.val:
                return False

            return same(r1.left, r2.left) and same(r1.right, r2.right)

        def dfs(root):
            if root is None:
                return False

            if same(root, B):
                return True

            if dfs(root.left):
                return True

            return dfs(root.right)

        return dfs(A)


A = '[1,2,3]'
B = '[3,1]'

A = '[3,4,5,1,2]'
B = '[4,1]'

A = TreeNode.fromStrList(A)
B = TreeNode.fromStrList(B)
print(Solution().isSubStructure(A, B))