二叉树节点
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
1 前序遍历
1.1 递归遍历
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
def helper(root):
if not root:
return []
res.append(root.val)
helper(root.left)
helper(root.right)
res = []
helper(root)
return res
1.2 迭代遍历
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
res = []
stack = []
node = root
while stack or node:
while node:
res.append(node.val)
stack.append(node)
node = node.left
node = stack.pop()
node = node.right
return res
2 中序遍历
2.1 递归遍历
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
def helper(root):
if not root:
return []
helper(root.left)
res.append(root.val)
helper(root.right)
res = []
helper(root)
return res
2.2迭代遍历
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
res = []
stack = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
res.append(node.val)
node = node.right
return res
3 后序遍历
3.1 递归遍历
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
def helper(root):
if not root:
return []
helper(root.left)
helper(root.right)
res.append(root.val)
res = []
helper(root)
return res
3.2 迭代遍历
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
res = []
stack = []
node = root
while stack or node:
while node:
res.append(node.val)
stack.append(node)
node = node.right
node = stack.pop()
node = node.left
return res[::-1]
4 层序遍历
import collections
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root == None:
return []
res = []
level = []
queue = collections.deque()
queue.append(root)
dummy = TreeNode(-1)
queue.append(dummy)
while len(queue) != 0:
node = queue.popleft()
if node == dummy:
res.append(level)
level = []
if len(queue) != 0:
queue.append(dummy)
else:
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res
二叉树基本操作
labuladong二叉树算法详解
带你套框架刷通二叉树(第一期)
带你套框架刷通二叉树(第二期)
带你套框架刷通二叉树(第三期)
二叉树的序列化和反序列化的几种方法
分治算法练习
递归算法练习
二叉树算法练习
欢迎交流,共同进步!谢谢!
网友评论