目录
1.先序遍历递归与非递归
def preorder_recursive(root):#先序遍历,递归版
if not root:
return None
print(root.val)
preorder_recursive(root.left)
preorder_recursive(root.right)
def preorder_iteration_1(root):#先序遍历,迭代版1
if not root:
return None
stack = []
node = root
while node or len(stack)>0:
while node:
print(node.val)
stack.append(node.left)
node = node.left
node = stack.pop()
node = node.right
def preorder_iteration_2(root):
if not root:
return None
stack = [root]
while len(stack)>0:
print(root.val)
if root.right:
stack.append(root.right)
if root.left:
stack.append(root.left)
root = stack.pop()
2.中序遍历递归与非递归
def inorder_recursive(root):#递归版本
if not root:
return None
inorder_recursive(root.left)
print(root.val)
inorder_recursive(root.right)
def inorder_iteration(root):#非递归版本
if not root:
return None
stack = []
node = root
while node or len(stack)>0:
while node:
stack.append(node)
node = node.left
node = stack.pop()
print(node.val)
node = node.right
3.后序遍历的递归与非递归
def postOrder_recursive(root):#递归版本
if not root:
return None
postOrder_recursive(root.left)
postOrder_recursive(root.right)
print(root.val)
def postOrder_iteration(root):
# 使用两个栈结构
# 第一个栈进栈顺序:左节点->右节点->根节点
# 第一个栈弹出顺序: 根节点->右节点->左节点
# 最后第二个栈依次出栈
if not root:
return None
stack1 = [root]
stack2 = []
while len(stack1)>0:
node = stack1.pop()
stack2.append(node)
if node.left:
stack1.append(node.left)
if node.right:
stack1.append(node.right)
while len(stack2)>0:
node = stack2.pop()
print(node.val)
4.层次遍历
def layer_iteration(root):
if not root:
return None
queue = [root]
while len(queue)>0:
node = queue.pop(0)
print(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
5.二叉树的最大深度
def Depth(root):
if not root:
return 0
Ldepth = Depth(root.left)
Rdepth = Depth(root.right)
return (max(Ldepth,Rdepth)+1)
6.验证二叉搜索树
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.valid(root, float('-inf'),float('inf')) #float('-inf'),float('inf')表示正负无穷
def valid(self, root, min, max):
if not root:
return True
if root.val >= max or root.val <= min:
return False
return self.valid(root.left, min, root.val) and self.valid(root.right, root.val, max)
7.从中序与后序遍历序列构造二叉树
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if len(postorder)==0:
return None
root = TreeNode(postorder[-1])
i = inorder.index(root.val)
root.left = self.buildTree(inorder[:i],postorder[:i])
root.right = self.buildTree(inorder[i+1:],postorder[i:len(postorder)-1])
return root
8.从前序与中序遍历序列构造二叉树
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if len(preorder)==0:
return None
root = TreeNode(preorder[0])
i = inorder.index(root.val)
root.left = self.buildTree(preorder[1:i+1],inorder[:i])
root.right = self.buildTree(preorder[i+1:],inorder[i+1:])
return root