菜鳥扣程式碼第十六天:leetcode第94題--二叉樹的中序遍歷
阿新 • • 發佈:2020-12-23
題目描述:
給定一個二叉樹的根節點 root ,返回它的 中序 遍歷。
示例 1:
輸入:root = [1,null,2,3]
輸出:[1,3,2]
示例 2:
輸入:root = []
輸出:[]
程式碼:
Definition for a binary tree node.
class TreeNode:
def init(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if root == None:
return []
stack = []
res = []
temp = root
while temp or stack:
if temp != None:
stack.append(temp)
temp = temp.left
else:
temp = stack.pop()
res. append(temp.val)
temp = temp.right
return res
測試:
輸入
[1,null,2,3]
輸出
[1,3,2]
預期結果
[1,3,2]
思路:
二叉樹的中序遍歷是非常經典的題目,在這裡藉助棧來實現非遞迴的遍歷方法。1.檢查二叉樹是否為空,if空則退出。2.else沿著左子樹一直到左子樹的最底部,並且移動過程中依次進棧。3.移動到左子樹最低端後,開始出棧,一個節點出棧後,進入該節點的右子樹,繼續執行2 。