Skip to content

Commit f9ab08d

Browse files
committed
Iterative Inorder traversal of tree
1 parent 9f2cbbe commit f9ab08d

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

1-100q/94.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
'''
2+
Given a binary tree, return the inorder traversal of its nodes' values.
3+
4+
Example:
5+
6+
Input: [1,null,2,3]
7+
1
8+
\
9+
2
10+
/
11+
3
12+
13+
Output: [1,3,2]
14+
15+
Follow up: Recursive solution is trivial, could you do it iteratively?
16+
'''
17+
18+
# Definition for a binary tree node.
19+
# class TreeNode(object):
20+
# def __init__(self, x):
21+
# self.val = x
22+
# self.left = None
23+
# self.right = None
24+
25+
class Solution(object):
26+
def inorderTraversal(self, root):
27+
"""
28+
:type root: TreeNode
29+
:rtype: List[int]
30+
"""
31+
if not root:
32+
return []
33+
34+
stack, result = [root], []
35+
while stack:
36+
if root.left:
37+
stack.append(root.left)
38+
root = root.left
39+
else:
40+
node = stack.pop()
41+
result.append(node.val)
42+
43+
if node.right:
44+
stack.append(node.right)
45+
root = node.right
46+
return result

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ Python solution of problems from [LeetCode](https://leetcode.com/).
9999
|98|[Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)| [Python](./1-100q/98.py)|Medium|
100100
|97|[Interleaving String](https://leetcode.com/problems/interleaving-string/)| [Python](./1-100q/97.py)|Hard|
101101
|95|[Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/)| [Python](./1-100q/95.py)|Medium|
102+
|94|[Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal)|[Python](./1-100q/94.py)|Medium|
102103
|93|[Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/)| [Python](./1-100q/93.py)|Medium|
103104
|92|[Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [Python](./1-100q/92.py)|Medium|
104105
|91|[Decode Ways](https://leetcode.com/problems/decode-ways/)| [Python](./1-100q/91.py)|Medium|

0 commit comments

Comments
 (0)