简繁EN

LeetCodeNo. 027

【LeetCode with Python】 94. Binary Tree Inorder Traversal

目錄

題目

原題頁面: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
    /
   3

return [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
    \
     5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".


分析

非遞迴中序遍歷二叉樹,每一個計算機和軟體專業的朋友大學上資料結構時都會遇到的題之一。總結成一句話就是:有左節點時將左節點壓棧,無左節點時出棧一個元素(棧如果是空的則遍歷結束),輸出該元素,然後如果該元素有右節點則將cur指標跳到該右節點。
關鍵在於還是要理解計算機遞迴的實現原理,然後用程式去加以模擬和實現。例如這題,就可以參考中序遍歷二叉樹的遞迴版本,在腦海中模擬一下整個遞迴過程,即子呼叫的進入和退出的順序,就能知道應該用一個棧去模擬這個過程,並且何時入棧和何時出棧。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:

# @param root, a tree node
# @return a list of integers
def inorderTraversal(self, root):

if None == root:
return [ ]

list = [ ]
stack = [ ]
cur = root
stack.append(cur)

while True:
if None != cur and None != cur.left:
stack.append(cur.left)
cur = cur.left
continue
if len(stack) >= 1:
cur = stack.pop()
list.append(cur.val)
cur = cur.right
else:
break
if None != cur:
stack.append(cur)

return list

本文地址:https://xnerv.wang/zh-tw/leetcode-binary-tree-inorder-traversal/