1.二叉树基础
文章讲解
满二叉树(只有度为0和2的结点)、完全二叉树(排列往左满)、二叉搜索树(排序树)、平衡二叉搜索树(AVL,高度差)!= 红黑树
2.二叉树遍历
该遍历建议返回值为空
1)前序遍历 (递归+迭代)
# 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 preorder(self, root, res):
if not root:
return
res.append(root.val)
self.preorder(root.left, res)
self.preorder(root.right, res)
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# res = []
# self.preorder(root, res)
# return res
# 迭代法实现,借助栈和队列都可实现
stack = []
res = []
if not root:
return res
stack.append(root)
while stack:
root = stack.pop()
res.append(root.val)
if root.right:
stack.append(root.right)
if root.left:
stack.append(root.left)
return res
2)后序遍历(递归+迭代)
迭代时:前序遍历和后序遍历的关系
# 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 postorder(self, root, res):
if not root:
return
self.postorder(root.left, res)
self.postorder(root.right, res)
res.append(root.val)
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# res = []
# self.postorder(root, res)
# return res
# 迭代法
stack = []
res = []
if not root:
return res
stack.append(root)
while stack:
root = stack.pop()
res.append(root.val)
if root.left:
stack.append(root.left)
if root.right:
stack.append(root.right)
return res[::-1]
3)中序遍历(递归+迭代)
不会写迭代啊!
迭代访问时一定是先访问根,如何做到访问先添加,直到将左边访问完再处理呢?
如果用while 一直遍历完左边会出现的问题是:
当回到左节点的根节点,此时又会重新将左节点加入到栈中造成死循环
# 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 inorder(self, root, res):
if not root:
return
self.inorder(root.left, res)
res.append(root.val)
self.inorder(root.right, res)
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# res = []
# self.inorder(root, res)
# return res
# 迭代法 左根右
res = []
stack = []
if not root:
return res
while stack or root: # 注意遍历条件以及为什么不一开始把root放入栈中
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
res.append(root.val)
root = root.right
return res