简繁EN

LeetCodeNo. 027

[LeetCode with Python] 94. Binary Tree Inorder Traversal

Contents

Problem

Problem page: https://leetcode.com/problems/binary-tree-inorder-traversal/
Topics: Tree, Hash Table, Stack
Difficulty: Medium
Similar problems: (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}".


Analysis

In-order traversal of a binary tree without recursion is one of those problems every computer science or software engineering major sees in a college data structures course. In one sentence: if there's a left child, push it onto the stack; if there's no left child, pop an element (if the stack is empty, the traversal is over), output it, and if it has a right child, move the cur pointer to that child.
The trick is to understand how a computer implements recursion and then write code to simulate it. For this problem, you can look at the recursive version of in-order traversal of a binary tree and run it in your head. Follow the order in which the recursive calls start and return, and you'll see that you need a stack to simulate the process and know when to push and when to pop.


Code

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

Article link: https://xnerv.wang/en/leetcode-binary-tree-inorder-traversal/