每日一題20201209(94. 二叉樹的中序遍歷)
阿新 • • 發佈:2020-12-09
94. 二叉樹的中序遍歷
遞迴
遞迴的實現很簡單,和前序遍歷類似,只是改變了append到陣列的順序。
# 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: TreeNode) -> List[int]: ans = [] def traversal(root): if root is None: return traversal(root.left) ans.append(root.val) traversal(root.right) traversal(root) return ans
迭代
遞迴維護了一個隱藏的stack,這裡我們需要手動維護這個stack.
以[1, null, 2, 3]為例,進棧出棧順序為:
[1] // 1進棧
[] // 由於1沒有left,1出棧
[2] // 2進棧
[2, 3] // 2的left進棧
[2] // 由於3沒有left 3出棧
[] // 2出棧
# 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: TreeNode) -> List[int]: stack = [] ans = [] while len(stack) > 0 or root is not None: # 如果root左節點一直有值,則一直進棧 while root is not None: stack.append(root) root = root.left current = stack.pop() ans.append(current.val) # 當前節點出棧後,把右節點賦給root,因為中序遍歷是 左孩子 根節點 右孩子 root = current.right return ans