class Solution: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: def recur(cur): if not cur: return [] recur(cur.left) res.append(cur.val) recur(cur.right) if not root: return [] res = [] recur(root) return res
使用局部变量的方法,获取到子树的信息后在一起进行处理
class Solution: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if not root: return [] left = self.inorderTraversal(root.left) right = self.inorderTraversal(root.right) res = [] # 中序是 “左中右” 的顺序 res.extend(left) res.append(root.val) res.extend(right) return res