Leetcode[94] Binary Tree Inorder Traversal
07 Nov 2015###Task1 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?
###Python ####Recursive
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ret = []
self.inorder(ret, root)
return ret
def inorder(self, ret, root):
if root == None:
return
self.inorder(ret, root.left)
ret.append(root.val)
self.inorder(ret, root.right)
####Iterative
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ret = []
stack = []
cur = root
while cur or len(stack) > 0:
while cur:
stack.append(cur)
cur = cur.left
l = stack.pop()
ret.append(l.val)
cur = l.right
return ret
###Easy to understand
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ret = []
stack = []
cur = root
while cur or len(stack) > 0:
if cur:
stack.append(cur)
cur = cur.left
elif len(stack) > 0:
newRoot = stack.pop()
ret.append(newRoot.val)
cur = newRoot.right
return ret
###Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) {
return res;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root;
while (!stack.isEmpty() || cur != null) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
TreeNode poped = stack.pop();
cur = poped.right;
res.add(poped.val);
}
return res;
}
}
###Points
- O(n) –> all the traversals are the same
- Iter: Need extra pointer to the right node (not easy)
- Iter: if node is not null, then all to stack until reach left most; otherwise if stack is not empty, pop current root add to ret and then move pointer to right(easier)