递归遍历
- 前序
# 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 preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def dfs(node):
if not node:
return None
ans.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return ans
- 后序
# 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 postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def dfs(node):
if not node:
return None
dfs(node.left)
dfs(node.right)
ans.append(node.val)
dfs(root)
return ans
- 中序
# 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 inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def dfs(node):
if not node:
return None
dfs(node.left)
ans.append(node.val)
dfs(node.right)
dfs(root)
return ans
迭代遍历
- 前序 中左右
结果进值–栈进右进左–出左,进值–栈进右进左-=栈出左 - 后序 左右中==倒序的中右左 将前序写法改一下然后逆序输出
结果进值–栈进左进右–出右,进值–栈进左进右-=栈出右 - 中序 栈一直进左-[指针为空=栈出左,保存值(中)-指针指右][指针不为空-栈一直进左]
## 前序遍历 迭代发法
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
ans = []
stack = []
stack.append(root)
while(stack):
node = stack.pop(-1)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
ans.append(node.val)
return ans
## 后序遍历 迭代法
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
ans = []
stack = [root]
while(stack):
node = stack.pop(-1)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
ans.append(node.val)
return ans[::-1]
## 中序遍历 迭代法
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
cur = root
stack = []
while(cur or stack):
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop(-1)
ans.append(cur.val)
cur = cur.right
return ans
层序遍历 BFS
· 迭代
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
ans = []
queue = [root]
while(queue):
N = len(queue)
temp = []
for i in range(N):
node = queue.pop(0)
if not node:
continue
temp.append(node.val)
queue.append(node.left) if node.left else None
queue.append(node.right) if node.right else None
ans.append(temp) if temp else None
return ans
· 递归BFS
暂时留着…