LeetCode热题100(hot100) 二

简单(二)

  • 1、[二叉树的中序遍历(94)](https://leetcode.cn/problems/binary-tree-inorder-traversal/)
    • 方法一:递归
    • 方法二:迭代
  • 2、[对称二叉树(101)](https://leetcode.cn/problems/symmetric-tree/)
  • 3、[二叉树的最大深度(104)](https://leetcode.cn/problems/maximum-depth-of-binary-tree/)
    • 方法一:DFS
    • 方法二:BFS
    • 4、[买卖股票的最佳时机(121)](https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/)
  • 5、[只出现一次的数字(136)](https://leetcode.cn/problems/single-number/)

1、二叉树的中序遍历(94)

LeetCode热题100(hot100) 二_第1张图片

方法一:递归

二叉树的中序遍历为左根右,针对树结构,可以使用递归的方法

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
            result = []
            def DFS(root):
                if not root:
                    return 
                DFS(root.left) # 深度搜索左枝
                result.append(root.val) # 保存根
                DFS(root.right) # 搜索右枝
            DFS(root)
            return result

方法二:迭代

利用栈来模拟中序遍历的过程
1、当树非空时,将当前的树节点存入栈中,并继续往左枝走
2、如果树节点为空,栈中存储的当前节点的左枝已经没了,弹出当前节点保存在结果列表中,继续探索当前节点的右枝。

class Solution(object):
	def inorderTraversal(self, root):
		"""
		:type root: TreeNode
		:rtype: List[int]
		"""
		res = []
		stack = []
		while stack or root:
			# 不断往左子树方向走,每走一次就将当前节点保存到栈中
			# 这是模拟递归的调用
			if root:
				stack.append(root)
				root = root.left
			# 当前节点为空,说明左边走到头了,从栈中弹出节点并保存
			# 然后转向右边节点,继续上面整个过程
			else:
				tmp = stack.pop()
				res.append(tmp.val)
				root = tmp.right
		return res

参考解析

2、对称二叉树(101)

LeetCode热题100(hot100) 二_第2张图片
只需递归的比较左子树和右子树是否相等即可
1、若左子树和右子树都为空,则返回True
2、若左子树和右子树只有一个为空,则返回False
3、若左子树与右子树在当前节点上的值不同,返回False
4、因为是镜像,所以要求左子树的左和右子树的右相同,左子树的右和右子树的左相同

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
          if not root:
             return True
          def DFS(left, right):
              if not left and not right:
                 return True
              elif not left or not right:
                 return False
              elif left.val != right.val:
                 return False
              return DFS(left.left, right.right) and DFS(left.right, right.left)
          return DFS(root.left, root.right)

3、二叉树的最大深度(104)

LeetCode热题100(hot100) 二_第3张图片

方法一:DFS

递归的比较左子树和右子树的深度,并取出最大值

class Solution:
    def maxDepth(self, root):
        if root is None: 
            return 0 
        else: 
            left_height = self.maxDepth(root.left) 
            right_height = self.maxDepth(root.right) 
            return max(left_height, right_height) + 1 

参考解答

方法二:BFS

利用队列q存储每一层的节点,每往下推进一层,就将q中存储的上一层节点清除并把深度加一

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
           return 0
        q = [root]
        depth = 0
        while q:
            n = len(q)
            for i in range(n):
                node = q.pop(0)
                if node.left:
                   q.append(node.left)
                if node.right:
                   q.append(node.right)
            depth += 1
        return depth

参考解答

4、买卖股票的最佳时机(121)

LeetCode热题100(hot100) 二_第4张图片
利用两个值价格最小值minprice和利润最大值maxprofit,求得最大利润

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        inf = int(1e9)
        minprice = inf
        maxprofit = 0
        for price in prices:
            maxprofit = max(price - minprice, maxprofit)
            minprice = min(price, minprice)
        return maxprofit

参考解答

5、只出现一次的数字(136)

LeetCode热题100(hot100) 二_第5张图片
要求具有线性时间复杂度,不使用额外的空间,因此使用位运算解答该题。
异或具有以下性质:任何数与其自身异或结果为0;任何数与0异或结果仍是原来的数
因为只有一个元素出现一次,其余元素均为2次,所以对数组中所有元素做异或,最终的结果就是只出现一次的元素。

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return reduce(lambda x, y: x ^ y, nums)  # reduce函数挨个取出数组中的元素,调用lambda进行计算

参考解答
LeetCode 热题100简单部分(二)完
知乎

你可能感兴趣的:(LeetCode热题100,leetcode,深度优先,算法)