# 算法之二叉树篇

### 二叉树的层次遍历

#### 解题思路

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

class Solution(object):
"""docstring for Solution"""
def levelOrderBottom(self, root):
if root == None: return []
res = []
def dfs(root):
queue = [root]
while queue:
nex = []
tmp = []
for node in queue:
tmp.append(node.val)
if node.left:
nex.append(node.left)
if node.right:
nex.append(node.right)
res.append(tmp)
queue = nex
dfs(root)
return res[::-1]

node1 = TreeNode(1)
node2 = TreeNode(3)
node3 = TreeNode(4)
node1.left = None
node1.right = node2
node2.left = node3
node2.right = None

solution = Solution()
print(solution.levelOrderBottom(node1))

• 时间复杂度：O(n)
• 空间复杂度：O(n)

### 对称二叉树

#### 解题思路

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

class Solution(object):
"""docstring for Solution"""
def isSymmetric(self, root):
def check(node1, node2):
if not node1 and not node2:
return True
elif not node1 or not node2:
return False
if node1.val != node2.val:
return False
return check(node1.left, node2.right) and check(node1.right, node2.left)
return check(root, root)

• 时间复杂度：O(n)
• 空间复杂度：O(n)

### 相同的树

#### 解题思路

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

class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q: return True
if p == None or q == None: return False
if p.val == q.val:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
else:
return False

• 时间复杂度：O(n)
• 空间复杂度：O(n)

### 二叉树的最大深度

#### 解题思路

BFS广度优先搜索，使用双端队列deque（因为性能比另外两种Queue好得多），在大循环内对二叉树的每个层做一次遍历，range(len(queue))使只遍历当前的层，每次大循环ans加1。由于每个节点仅访问一次，所以时间复杂度O(n)

import collections

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

class Solution(object):
"""docstring for Solution"""
def maxDepth(self, root):
if not root: return 0
queue = collections.deque()
# deque的append：在列表右边添加一个元素
queue.append(root)
ans = 0
while queue:
ans += 1
for i in range(len(queue)):
# deque的popleft：在列表的左边弹出一个元素
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return ans

• 时间复杂度：O(n)
• 空间复杂度：O(n)