classSolution: definorderTraversal(self, root: TreeNode) -> List[int]: f = self.inorderTraversal return f(root.left) + [root.val] + f(root.right) if root else []
非递归(堆栈)
参考评论区
1 2 3 4 5 6 7 8 9 10 11
classSolution: definorderTraversal(self, root: TreeNode) -> List[int]: res, st, n = [], [], root while n or st: while n: st.append(n) n = n.left n = st.pop() res.append(n.val) n = n.right return res
莫里斯遍历
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: definorderTraversal(self, root: TreeNode) -> List[int]: res, curr = [], root while curr isnotNone: if curr.left isNone: res.append(curr.val) curr = curr.right else: pre = curr.left while pre.right isnotNone: pre = pre.right pre.right, curr.left, curr, = curr, None, curr.left return res