前序
给你二叉树的根节点 root ,返回它节点值的 前序 遍历
# 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]:
if not root:
return []
left=self.preorderTraversal(root.left)
right=self.preorderTraversal(root.right)
return [root.val]+left+right
中序:
给定一个二叉树的根节点 root ,返回 它的 中序 遍历
# 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]:
if root is None:
return []
left = self.inorderTraversal(root.left)
right=self.inorderTraversal(root.right)
return left+[root.val]+right
后序:
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
# 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]:
if root is None:
return []
left = self.postorderTraversal(root.left)
right=self.postorderTraversal(root.right)
return left+right+[root.val]