class Solution:
def preorderTraversal(self, root):
#option 1: recursion version
#def recursion(T): return [] if T is None else [T.val] + recursion(T.left) + recursion(T.right)
#return recursion(root)
# option 2: iterative version
res, stack = [], [root]
if root:
while stack:
current=stack.pop()
res.append(current.val)
if current.right: stack.append(current.right)
if current.left: stack.append(current.left)
return res
def inorderTraversal(self, root):
#option 1: recursion version
#def recursion(T): return [] if T is None else recursion(T.left) + [T.val] + recursion(T.right)
#return recursion(root)
# option 2: iterative version
res, stack, current = [], [], root
while stack or current:
if current:
stack.append(current)
current = current.left
else:
parent = stack.pop()
res.append(parent.val)
current = parent.right
return res
def postorderTraversal(self, root):
#option 1: recursion version
#def recursion(T): return [] if T is None else recursion(T.left) + recursion(T.right) + [T.val]
#return recursion(root)
# option 2: iterative version
# http://www.cnblogs.com/zuoyuan/p/3720846.html
res, stack, prev = [], [root], None
if root:
while stack:
curr=stack[-1]
if (curr.left == None and curr.right == None) or (prev and (prev == curr.left or prev == curr.right)):
res.append(curr.val)
stack.pop()
prev=curr
else:
if curr.right: stack.append(curr.right)
if curr.left: stack.append(curr.left)
return res
Blog Archive
-
▼
2014
(190)
-
▼
August
(23)
- 十道海量数据处理面试题与十个方法大总结 - 结构之法 算法之道 - 博客频道 - CSDN.NET
- Backtracking | Set 2 (Rat in a Maze) - GeeksforGeeks
- Amazon Jobs | Push the Envelope with Amazon’s Spee...
- [leetcode]Longest Consecutive Sequence @ Python - ...
- AIDasr - 博客园
- Find all combinations of coins when given some dol...
- [leetcode]Edit Distance @ Python - 南郭子綦 - 博客园
- Google APAC 2015 University Graduates Test
- My Own Notes: LeetCode (Python): Flatten Binary Tr...
- LeetCode题解整理版(二) | Coding 4 Fun
- Binary Tree Preorder Inorder Postorder Traversal ...
- Binary Tree Level Order Traversal II | LeetCode OJ
- LeetCode — Binary Tree Preorder Traversal(C++ Java...
- 前女友因为我没进Google而和我分手 (转载) - 未名空间(mitbbs.com)
- [Mitbbs]FB的intern和准备的经历 - - 博客频道 - CSDN.NET
- Google coding Style Guide
- LeetCode OJ --问题与解答 前言
- Lexi's Leetcode solutions
- LeetCode 分类
- Can Mobile Technologies and Big Data Improve Healt...
- 喀什葛尔胡杨歌词
- Study: Noise-Induced Hearing Loss Alters Brain Res...
- How to Focus
-
▼
August
(23)
Thursday, August 14, 2014
Binary Tree Preorder Inorder Postorder Traversal solution.
Labels:
binary tree,
inorder,
Leetcode,
postorder,
preorder
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment