題目
原題頁面:https://leetcode.com/problems/binary-tree-inorder-traversal/
題目型別:Tree, Hash Table, Stack
難度評價:Medium
類似題目:(M) Validate Binary Search Tree, (M) Binary Tree Preorder Traversal, (H) Binary Tree Postorder Traversal, (M) Binary Search Tree Iterator, (M) Kth Smallest Element in a BST, (H) Closest Binary Search Tree Value II, (M) Inorder Successor in BST
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree{1,#,2,3},1 \ 2 / 3return
[1,3,2].Note: Recursive solution is trivial, could you do it iteratively?
confused what
"{1,#,2,3}"means?OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}".
分析
非遞迴中序遍歷二叉樹,每一個計算機和軟體專業的朋友大學上資料結構時都會遇到的題之一。總結成一句話就是:有左節點時將左節點壓棧,無左節點時出棧一個元素(棧如果是空的則遍歷結束),輸出該元素,然後如果該元素有右節點則將cur指標跳到該右節點。
關鍵在於還是要理解計算機遞迴的實現原理,然後用程式去加以模擬和實現。例如這題,就可以參考中序遍歷二叉樹的遞迴版本,在腦海中模擬一下整個遞迴過程,即子呼叫的進入和退出的順序,就能知道應該用一個棧去模擬這個過程,並且何時入棧和何時出棧。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-binary-tree-inorder-traversal/
