数据结构与算法 学习笔记(7):二叉树和树
本次文章主要记录了最近在LeetCode上刷的有关与二叉树和树的题目,主要涉及深度优先、广度优先、递归与非递归,并给出了算法和算法分析,如有错漏或更好的解法,欢迎到文末github中提交RP。
注:题号与LeetCode对应
题目1:100. Same Tree
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
"""
方法1: 深度优先 递归实现
方法2: 深度优先 栈实现
方法3: 广度优先 队列实现
注意:广度优先 没有合适的递归实现,非要递归也没有意义。
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
# # method 1: recursion DFS
# if not p and not q:
# return True
# if p and q:
# if p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right):
# return True
# else:
# return False
# # method 2: DFS with stack
# stack = [(p, q)]
# while stack:
# n1, n2 = stack.pop()
# if n1 and n2 and n1.val == n2.val:
# stack.append((n1.right, n2.right))
# stack.append((n1.left, n2.left))
# elif not n1 and not n2:
# continue
# else:
# return False
# return True
# method 3: BFS with queue
queue = [(p, q)]
while queue:
n1, n2 = queue.pop(0)
if n1 and n2 and n1.val == n2.val:
queue.append((n1.left, n2.left))
queue.append((n1.right, n2.right))
elif not n1 and not n2:
continue
else:
return False
return True
题目2:101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
"""
方法1:采用递归的思想
0.特殊情况:树为空,按题意返回True
1.不为空,则判断其左右子树是否镜像
2.递归判断镜像与否
完成!
时间复杂度:O(n),要遍历所有结点。
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# method 1 recursion
if root is None: #空树与否
return True
else:
return self.isMirror(root.left, root.right)
def isMirror(self, left, right):
if left is None and right is None: #左右子树存在与否
return True
if left is None or right is None:
return False
if left.val == right.val: # 存在且相等 递归判断左子树和右子树是否镜像
outPair = self.isMirror(left.left, right.right)
inPiar = self.isMirror(left.right, right.left)
return outPair and inPiar
else:
return False
题目3:104. Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
"""
method 1: 递归
0. 判空,返回树深为0
1. 非空,返回 1 + 子树深度(取左右子树中深度最深的那个数字)
2. 求子树深度:
判空,返回子树深度为 0,总深度为 1+0 =1
非空,返回 1 + 该子树的子树的深度(取左右子树相比较深的)
3. 依此递归实现
method 2: 栈 非递归
method 3: 队列 非递归
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# method 1: recursion
# if not root:
# return 0
# return 1 + max(self.maxDepth(root.left),self.maxDepth(root.right))
# # method 2 : stack
# if not root:
# return 0
# tstack, h = [root], 0
# while tstack:
# nextlevel = []
# while tstack:
# top = tstack.pop()
# if top.left:
# nextlevel.append(top.left)
# if top.right:
# nextlevel.append(top.right)
# tstack = nextlevel
# h += 1
# return h
# method 3 : queue
if not root:
return 0
queue, h = [root], 0
while queue:
nextlevel = []
while queue:
top = queue.pop(0)
if top.left:
nextlevel.append(top.left)
if top.right:
nextlevel.append(top.right)