关于树的常见编程题

  1. 获取二叉树中和最大的路径【leetcode124】
    二叉树每一个节点都有一个数,求和最大的路径。
    注意:这是所有路径,包括一个叶子节点到另一个叶子节点的路径。
def recursion(root, m):
    if root is None:
        return 0
    left = recursion(root.left, m)
    right = recursion(root.right, m)
    ret = max(left, right, 0) + root.val
    m[0] = max(m[0], ret, left+right+root.val)
    return ret

def maxPathSum(root):
    if root is None:
        return 0
    m = [root.val]
    recursion(root, m)
    return m[0]
  1. 二叉树的最小深度与最大深度【leetcode111、104】
# 以下是二叉树的最小深度的求解
def minDepth(root):
    if root is None:
        return 0
    if root.left is not None:
        if root.right is not None:
            return min(minDepth(root.left), minDepth(root.right)) + 1
        else:
            return minDepth(root.left) + 1
    elif root.right is not None:
        return minDepth(root.right) + 1
    else:
        return 1

#以下是二叉树最大深度的求解
def maxDepth(root):
    return 0 if root is None else max(maxDepth(root.left), maxDepth(root.right))+1
  1. 判断二叉树是否平衡【leetcode110】
    每个节点的左子树与右子树的高度之差至多为1则是平衡二叉树。
def recursion(root, h):
    if root is None:
        h[0] = 0
        return True
    lh, rh = [0], [0]
    if not recursion(root.left, lh):
        return False
    if not recursion(root.right, rh):
        return False
    h[0] = max(lh[0], rh[0]) + 1
    return abs(lh[0] - rh[0]) <= 1

def isBalanced(root):
    return recursion(root, [0])
  1. 判断两个二叉树是否相同【leetcode100】
def isSame(root1, root2):
    if root1 is None:
        return root2 is None
    else:
        if root2 is None:
            return False
        else:
            return root1.val == root2.val and isSame(root1.left, root2.left) and isSame(root1.right, root2.right)
  1. 判断二叉树是否对称【leetcode101】
def recursion(root1, root2):
    if root1 is None:
        return root2 is None
    else:
        if root2 is None:
            return False
        else:
            return root1.val == root2.val and recursion(root1.left, root2.right) and recursion(root2.left, root1.right)

def isSymmetrical(root):
    if root is None:
        return True
    return recursion(root.left, root.right)
  1. 判断二叉树是否为二叉搜索树【leetcode98、173】
    对于任意一个节点,其左子树比它小,其右子树比它大
# 该方法采用中序遍历保存所有值,可优化为只保存一个值,每次去比较即可
def inorderTraversal(root, arr):
    if root is not None:
        inorderTraversal(root.left, arr)
        arr.append(root.val)
        inorderTraversal(root.right, arr)
        
def isSearchTree(root):
    arr = []
    inorderTraversal(root, arr)
    i = 1
    while i < len(arr):
        if arr[i-1] >= arr[i]:
            return False
        i += 1
    return True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值