题解 | #二叉树的前序遍历#
二叉树的前序遍历
https://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
二叉树遍历
思路:
- 没有返回,用一个self变量保存遍历的值。
- 用递归
前序遍历 - 根左右
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # @param root TreeNode类 # @return int整型一维数组 class Solution: res = [] def preorderTraversal(self , root: TreeNode) -> List[int]: # 根左右 if root == None: return self.res.append(root.val) self.preorderTraversal(root=root.left) self.preorderTraversal(root=root.right) return self.res
中序遍历 - 左根右
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # @param root TreeNode类 # @return int整型一维数组 # 左根右 class Solution: res = [] def inorderTraversal(self , root: TreeNode) -> List[int]: # write code here if root == None: return self.inorderTraversal(root.left) self.res.append(root.val) self.inorderTraversal(root.right) return self.res
后序遍历 - 左右根
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # @param root TreeNode类 # @return int整型一维数组 # 左右根 class Solution: res = [] def postorderTraversal(self , root: TreeNode) -> List[int]: # write code here if root == None: return self.postorderTraversal(root.left) self.postorderTraversal(root.right) self.res.append(root.val) return self.res