LeetCode——难度等级Easy的前20~30道题(题号100~119)

版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。如有错误,欢迎指出,我会及时修改 https://blog.csdn.net/yukinoai/article/details/88917556

目录

100.相同的树    Same Tree    

101.对称二叉树    Symmetric Tree 

104.二叉树的最大深度    Maximum Depth of Binary Tree

107.二叉树的层次遍历II    Binary Tree Level Order Traversal II

108.将有序数组转换为二叉搜索树    Convert Sorted Array to Binary Search Tree  

110.平衡二叉树    Balanced Binary Tree 

111.二叉树最小深度    Minimum Depth of Binary Tree

112.路径总和   Path Sum

118.杨辉三角   Pascal's Triangle

119.杨辉三角II    Pascal's Triangle II


注:有关二叉树的题中引用的tree文件可以参考:https://blog.csdn.net/yukinoai/article/details/88725168

将这个网址中的程序命名为tree.py与题目文件放在一个文件夹即可

这个文件可以简单创建和表示二叉树,方便程序的调试。

100.相同的树    Same Tree    

"""
给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 1:

输入:       1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

输出: true
示例 2:

输入:      1          1
          /           \
         2             2

        [1,2],     [1,null,2]

输出: false
示例 3:

输入:       1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

输出: false
"""


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


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

101.对称二叉树    Symmetric Tree 

"""
题目描述
评论 (122)
题解
提交记录
给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3
"""


import tree


class Solution(object):
    def isSymmetric1(self, node):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def helper(root, mirror):
            if not root and not mirror:
                return True
            if root and mirror and root.val == mirror.val:
                return helper(root.left, mirror.right) and helper(root.right, mirror.left)
            return False
        return helper(node, node)

    def isSymmetric2(self, root):
        def isSame(p, q):
            if p and q and p.val == q.val:
                return isSame(p.left, q.right) and isSame(p.right, q.left)
            if not p:
                return not q
            return False
        if not root:
            return True
        return isSame(root.left, root.right)


s = Solution()

a = [1, 2, 2, 3, 4, 4, 3]

t1 = tree.listcreattree(None, a, 0)
tree.printTree(t1)
print(s.isSymmetric2(t1))

b = [1, 2, 2, '#', 3, '#', 3]

t2 = tree.listcreattree(None, b, 0)
tree.printTree(t2)
print(s.isSymmetric2(t2))

104.二叉树的最大深度    Maximum Depth of Binary Tree

"""
给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。
"""

import tree


class Solution:
    def maxDepth(self, root):
        if not root:
            return 0
        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1


a = [3, 9, 20, '#', '#', 15, 7]
t = tree.listcreattree(None, a, 0)
s = Solution()
tree.printTree(t)
print(s.maxDepth(t))

107.二叉树的层次遍历II    Binary Tree Level Order Traversal II

"""
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其自底向上的层次遍历为:

[
  [15,7],
  [9,20],
  [3]
]
"""

import tree
from collections import deque


def levelOrderBottom1(root):
    if not root:
        return []
    ans = [[root.val]]
    queue = deque([root])
    while queue:
        levelans = []
        for _ in range(0, len(queue)):
            root = queue.popleft()
            if root.left:
                levelans.append(root.left.val)
                queue.append(root.left)
            if root.right:
                levelans.append(root.right.val)
                queue.append(root.right)
        if levelans:
            ans.append(levelans)
    return ans[::-1]


def levelOrderBottom2(root):
    if root is None:
        return []
    q = [root]
    res = []
    while q:
        tmp = []
        q2 = []
        for item in q:
            tmp.append(item.val)
            if item.left:
                q2.append(item.left)
            if item.right:
                q2.append(item.right)
        res.append(tmp)
        q = q2
    return res[::-1]


a = [3, 9, 20, '#', '#', 15, 7]
t = tree.listcreattree(None, a, 0)
c = levelOrderBottom2(t)
print(c)

108.将有序数组转换为二叉搜索树    Convert Sorted Array to Binary Search Tree  

"""
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定有序数组: [-10,-3,0,5,9],

一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5
"""
import tree


class Solution:
    def sortedArrayToBST(self, nums):
        if nums:
            midPos = len(nums) // 2
            mid = nums[midPos]
            root = tree.TreeNode(mid)
            root.left = self.sortedArrayToBST(nums[:midPos])
            root.right = self.sortedArrayToBST(nums[midPos+1:])
            return root


s = Solution()
a = [0, -3, 9, -10, 5]
tr = s.sortedArrayToBST(a)
tree.printTree(tr)

110.平衡二叉树    Balanced Binary Tree 

"""
给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7
返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
返回 false 。
"""
import tree


class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def dfs(p):
            if not p:
                return 0

            left = dfs(p.left)
            right = dfs(p.right)
            if left == -1 or right == -1:
                return -1
            if abs(left - right) > 1:
                return -1
            return 1 + max(left, right)
        if dfs(root) == -1:
            return False
        return True


s = Solution()
a = [3, 9, 20, '#', '#', 15, 7]
t = tree.listcreattree(None, a, 0)
c = s.isBalanced(t)
d = [1, 2, 2, 3, 3, '#', '#', 4, 4]
f = tree.listcreattree(None, d, 0)
g = s.isBalanced(f)
tree.printTree(f)
print(g)

111.二叉树最小深度    Minimum Depth of Binary Tree

"""
给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回它的最小深度  2.
"""
import tree


class Solution(object):
    def minDepth1(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        left = self.minDepth(root.left)
        right = self.minDepth(root.right)
        if not left and not right:
            return 1
        elif not left:
            return right + 1
        elif not right:
            return left + 1
        else:
            return min(left, right) + 1

    def minDepth2(self, root):
        if not root:
            return 0
        q = [root]
        height = 1
        while q:
            q2 = []
            for i in q:
                if i.left:
                    q2.append(i.left)
                if i.right:
                    q2.append(i.right)
                if not i.right and not i.left:
                    return height
            height += 1
            q = q2
        return height


s = Solution()
a = [3, 9, 20, '#', '#', 15, 7]
t = tree.listcreattree(None, a, 0)
tree.printTree(t)
c = s.minDepth2(t)
print(c)

112.路径总和   Path Sum

"""
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2
"""


import tree
from collections import deque


class Solution(object):
    def hasPathSum1(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if root:
            queue = deque([(root, root.val)])
            while queue:
                p, s = queue.popleft()
                left, right = p.left, p.right
                if left:
                    queue.append((p.left, s + p.left.val))
                if right:
                    queue.append((p.right, s + p.right.val))
                if not left and not right and s == sum:
                    return True
            return False
        return False

    def hasPathSum(self, root, sum):
        if root is None:
            return False
        elif sum == root.val and root.left is None and root.right is None:
            return True
        else:
            return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)


s = Solution()
a = [5, 4, 8, 11, '#', 13, 4, 7, 2, '#', '#', '#', '#', '#', 1]
t = tree.listcreattree(None, a, 0)
tree.printTree(t)
c = s.hasPathSum(t, 22)
print(c)

118.杨辉三角   Pascal's Triangle

"""
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
"""


def generate1(numRows):
    if numRows is 0:
        return []
    if numRows is 1:
        return [[1]]
    if numRows is 2:
        return [[1], [1, 1]]
    start = [[1], [1, 1]]
    for i in range(2, numRows):
        temp = []
        for j in range(0, i-1):
            temp.append(start[i-1][j]+start[i-1][j+1])
        temp = [1] + temp + [1]
        start.append(temp)
    return start


def generate2(numRows):
    line = []
    for i in range(numRows):
        line.append([1])
        for j in range(1, i+1):
            if j == i:
                line[i].append(1)
            else:
                line[i].append(line[i-1][j-1]+line[i-1][j])
    return line


c = generate2(6)
print(c)

119.杨辉三角II    Pascal's Triangle II

"""
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 3
输出: [1,3,3,1]
进阶:

你可以优化你的算法到 O(k) 空间复杂度吗?

在真实的面试中遇到过这道题?
"""


def getRow1(rowIndex):
    if rowIndex is 0:
        return [1]
    if rowIndex is 1:
        return [1, 1]
    start = [1, 1]
    for i in range(2, rowIndex+1):
        temp = []
        for j in range(0, i-1):
            temp.append(start[j]+start[j+1])
        start = [1] + temp + [1]
    return start


def getRow2(rowIndex):
    if rowIndex is 0:
        return [1]
    list1 = []
    i = j = 1
    h = rowIndex
    while i < rowIndex:
        list1.append(h//j)
        h *= rowIndex-i
        j *= i + 1
        i += 1
    list1.append(1)
    list1.insert(0, 1)
    return list1


c = getRow2(3)
print(c)

猜你喜欢

转载自blog.csdn.net/yukinoai/article/details/88917556