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 / 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}".
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 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-binary-tree-inorder-traversal/
