给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
输入:root = [1,null,2,3]
输出:[1,3,2]
输入:root = []
输出:[]
输入:root = [1]
输出:[1]
输入:root = [1,2]
输出:[2,1]
输入:root = [1,null,2]
输出:[1,2]
树中节点数目在范围 [0, 100] 内-100 <= Node.val <= 100 题目分析
简单地中序遍历,直接套用模板即可。代码如下:
# 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 = rightclass Solution: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if not root: return [] return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)