Ejemplo n.º 1
0
        right = maxDepth(root.right)
        if left < 0 or right < 0 or abs(left - right) > 1:
            return -1
        return max(left, right) + 1

    h = maxDepth(root)
    return h >= 0


def isBalanced(root: 'TreeNode') -> bool:
    def maxDepth(root):
        if not root:
            return 0
        return max(maxDepth(root.left), maxDepth(root.right)) + 1

    if not root:
        return True
    left = maxDepth(root.left)
    right = maxDepth(root.right)

    return abs(left - right) <= 1 and isBalanced(root.left) and isBalanced(
        root.right)


root1 = lstToTreeNode([3, 9, 20, None, None, 15, 7])
root2 = lstToTreeNode([1, 2, 2, 3, 3, None, None, 4, 4])
root3 = lstToTreeNode([1, 2, 2, 3, None, None, 3, 4, None, None, 4])
# print(isBalanced(root1))
# print(isBalanced(root2))
print(isBalanced(root3))
Ejemplo n.º 2
0

def isSameTree1(p, q):
    if not p and not q:
        return True
    if (p and not q) or (not p and q):
        return False
    return p.val == q.val and isSameTree(p.left, q.left) and isSameTree(
        p.right, q.right)


def isSameTree(p, q):
    stack = [(p, q)]
    while stack:
        r1, r2 = stack.pop()
        if (r1 and not r2) or (not r1 and r2) or (r1 and r2
                                                  and r1.val != r2.val):
            return False
        if r1 and r2:
            stack.append((r1.left, r2.left))
            stack.append((r1.right, r2.right))
    return True


r1 = lstToTreeNode([1, 2])
r2 = lstToTreeNode([1, None, 2])
r3 = lstToTreeNode([1, 2, 3])
r4 = lstToTreeNode([1, 2, 3])
print(isSameTree(r1, r2))
print(isSameTree(r3, r4))
Ejemplo n.º 3
0
#           1                         2
#          / \                       / \
#         3   2                     1   3
#        /                           \   \
#       5                             4   7
# Output:
# Merged tree:
# 	     3
# 	    / \
# 	   4   5
# 	  / \   \
# 	 5   4   7

from leetcode.tree import TreeNode, lstToTreeNode, treeNodeToLst


def mergeTrees(t1: TreeNode, t2: TreeNode) -> TreeNode:
    if t1 is None or t2 is None:
        return t1 or t2
    t1.val += t2.val
    t1.left = mergeTrees(t1.left, t2.left)
    t1.right = mergeTrees(t1.right, t2.right)
    return t1


root = mergeTrees(lstToTreeNode([1, 3, 2, 5]),
                  lstToTreeNode([2, 1, 3, None, 4, None, 7]))

print(root)
print(treeNodeToLst(root))
Ejemplo n.º 4
0
import collections
from leetcode.tree import lstToTreeNode


def maxDepth(root: 'TreeNode') -> int:
    if not root:
        return 0
    return max(maxDepth(root.left), maxDepth(root.right)) + 1


def maxDepth2(root: 'TreeNode') -> int:
    if not root:
        return 0
    dq = collections.deque([root])
    depth = 0
    while dq:
        n = len(dq)
        for i in range(n):
            node = dq.popleft()
            if node.left:
                dq.append(node.left)
            if node.right:
                dq.append(node.right)
        depth += 1
    return depth


root = lstToTreeNode([3, 9, 20, None, None, 15, 7])
print(maxDepth(root))
print(maxDepth2(root))
Ejemplo n.º 5
0
    cache = {}
    return search(root, True)


# def rob(self, root):
#     """
#     :type root: TreeNode
#     :rtype: int
#     """
#     def robSub(root):
#         if not root:
#             return [0, 0]
#
#         left = robSub(root.left);
#         right = robSub(root.right);
#         res = [0, 0]
#
#         res[0] = max(left[0], left[1]) + max(right[0], right[1])
#         res[1] = root.val + left[0] + right[0]  # left[0] 表示left节点没有被rob,left[1] 表示left节点被rob
#         return res
#
#     res = robSub(root)
#     return max(res[0], res[1])

# lst = [53, 2, 3, 4, 3, 1, None, 67]
lst = [3, 2, 3, None, 3, None, 1]

lst2 = [3, 4, 5, 1, 3, None, 1]
tree = lstToTreeNode(lst2)
print(rob(tree))
Ejemplo n.º 6
0
#         5
#          \
#           6

from leetcode.tree import lstToTreeNode, treeNodeToLst
# from leetcode.listnode import link2Lst


class Solution:
    def __init__(self):
        self.prev = None

    def flatten(self, root: 'TreeNode') -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        if not root:
            return
        self.flatten(root.right)
        self.flatten(root.left)
        root.right = self.prev
        root.left = None
        self.prev = root


s = Solution()
root = lstToTreeNode([1, 2, 5, 3, 4, None, 6])
s.flatten(root)
print(treeNodeToLst(root))
# print("ok")
Ejemplo n.º 7
0
# not success
def hasPathSum(root: 'TreeNode', n: int) -> bool:
        if root is None:
            return False
        if root.left is None and root.right is None and root.val == n:
            return True
        return hasPathSum(root.left, n - root.val) or hasPathSum(root.right, n - root.val)


def hasPathSum1(root: 'TreeNode', n: int) -> bool:
    if not root:
        return False
    stack = [(root, n)]
    while stack:
        r, s = stack.pop()
        if r.left is None and r.right is None and r.val == s:
            return True
        if r.left:
            stack.append((r.left, s - r.val))
        if r.right:
            stack.append((r.right, s - r.val))
    return False


# root1 = lstToTreeNode([5,4,8,11,None,13,4,7,2,None,None,None,1])
root = lstToTreeNode([5,4,8,None,11])

print(hasPathSum1(root, 9))

print(treeNodeToLst(root))
Ejemplo n.º 8
0
def preorderTraversal2(root: 'TreeNode') -> 'List[int]':
    result = []
    stack = []
    cur = root
    while cur or stack:
        while cur:
            result.append(cur.val)
            stack.append(cur)
            cur = cur.left
        cur = stack.pop()
        cur = cur.right
    return result


def preorderTraversal3(root: 'TreeNode') -> 'List[int]':
    result = []
    stack = [root]
    while stack:
        cur = stack.pop()
        if cur:
            result.append(cur.val)
            stack.append(cur.right)
            stack.append(cur.left)
    return result


root = lstToTreeNode([1, None, 2, 3])
print(preorderTraversal(root))
print(preorderTraversal2(root))
print(preorderTraversal3(root))
Ejemplo n.º 9
0
def isSymmetric2(root: 'TreeNode') -> bool:
    def isMirror(p, q):
        if p is None and q is None:
            return True
        if p is None or q is None:
            return False
        return p.val == q.val and isMirror(p.left, q.right) and isMirror(
            p.right, q.left)

    return isMirror(root, root)


def isSymmetric(root: 'TreeNode') -> bool:
    stack = [(root, root)]
    while stack:
        r1, r2 = stack.pop()
        if (r1 and not r2) or (not r1 and r2) or (r1 and r2
                                                  and r1.val != r2.val):
            return False
        if r1 and r2:
            stack.append((r1.left, r2.right))
            stack.append((r1.right, r2.left))
    return True


r1 = lstToTreeNode([1, 2, 2, 3, 4, 4, 3])
print(isSymmetric(r1))
r2 = lstToTreeNode([1, 2, 2, None, 3, None, 3])
print(isSymmetric(r2))
Ejemplo n.º 10
0
        if cur:
            if visited:
                result.append(cur.val)
            else:
                stack.append((cur, True))
                stack.append((cur.right, False))
                stack.append((cur.left, False))
    return result


# The 3rd uses modified preorder (right subtree first). Then reverse the result.
def postorderTraversal3(root: 'TreeNode') -> 'List[int]':
    result = []
    stack = [root]
    while stack:
        cur = stack.pop()
        if cur:
            result.append(cur.val)
            stack.append(cur.left)
            stack.append(cur.right)
    return result[::-1]


root = lstToTreeNode([1, 2, 3, None, None, 4])
print(postorderTraversal(root))
print(postorderTraversal2(root))
print(postorderTraversal3(root))

import numpy as np
import matplotlib.pyplot as plt
Ejemplo n.º 11
0
# limits if they are available. Then one repeats the same step recursively for left and right subtrees.

from leetcode.tree import lstToTreeNode


def isValidBST(root: 'TreeNode') -> bool:
    if root is None:
        return True

    def isValid(node, lo, hi):
        if lo is not None and node.val <= lo:
            return False
        if hi is not None and node.val >= hi:
            return False
        left = isValid(node.left, lo, node.val) if node.left else True
        if left:
            right = isValid(node.right, node.val, hi) if node.right else True
            return right
        else:
            return False

    return isValid(root, None, None)


#
# print(isValidBST(lstToTreeNode([2, 1, 3])))
# print(isValidBST(lstToTreeNode([5, 1, 4, None, None, 3, 6])))
# print(isValidBST(lstToTreeNode([10, 5, 15, None, None, 6, 20])))

print(isValidBST(lstToTreeNode([0, None, -1])))
Ejemplo n.º 12
0
def isSameTree(p, q):
    """
    :type p: TreeNode
    :type q: TreeNode
    :rtype: bool
    """
    if p is None and q is None:
        return True
    elif p is None or q is None:
        return False
    if p.val == q.val:
        left = isSameTree(p.left, q.left)
        right = isSameTree(p.right, q.right)
        return left and right
    return False
    # stack = [(p, q)]
    # while stack:
    #     r1, r2 = stack.pop()
    #     if (r1 and not r2) or (not r1 and r2) or (r1 and r2 and r1.val != r2.val):
    #         return False
    #     if r1 and r2:
    #         stack.append((r1.left, r2.left))
    #         stack.append((r1.right, r2.right))
    # return True


p = lstToTreeNode([1, 2, 3, 4])
q = lstToTreeNode([1, 2, 3, 5])
print(isSameTree(p, q))