144.二叉树的前序遍历
测试代码main()
class TreeNode:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
from typing import List
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
s = Solution()
# 构造一个二叉树,此处省略了构造函数的实现
# tree = TreeNode()
tree = TreeNode(1)
tree.right = TreeNode(2)
tree.right.left = TreeNode(3)
print(s.preorderTraversal(tree)) # 输出 [1, 2, 3]
从测试main()中的到二叉树由如下:
运行代码:
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
result=[]
def trverse(root):
if root==None:
return
result.append(root.val)
trverse(root.left)
trverse(root.right)
trverse(root)
return result
代码运行逻辑:
踩坑1:
我做这道题的时候,想不通return为啥不直接结束,返回结果到main,后来我才想明白,是递归调用的原因。
(30条消息) return的四种用法_return函数的用法_你的猫跑掉了!!的博客-CSDN博客
94.二叉树的中序遍历
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
result=[]
def trverse(root):
if root == None:
return
trverse(root.left)
result.append(root.val)
trverse(root.right)
trverse(root)
return result
145.二叉树的后序遍历
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
result = []
def trverse(root):
if root == None:
return
trverse(root.left)
trverse(root.right)
result.append(root.val)
trverse(root)
return result
(今天刷到这,有点受不了,得缓缓)