二叉树的递归遍历
解题思路:要在结构上理解前中后序的区别:前序递归(从根到子)中左右,中序递归(从左向右)左中右,后续递归(从子到根右左中)。
# 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]:
returnList=[]
return self.frontSort(root,returnList)
def frontSort(self,root:Optional[TreeNode],returnList:List[int])-> List[int]:
if not root:
return returnList
returnList.append(root.val)
self.frontSort(root.right,returnList)
self.frontSort(root.left,returnList)
return returnList