Link: http://oj.leetcode.com/problems/binary-tree-inorder-traversal/
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? > read more on how binary tree is serialized on OJ.
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}"
.Recusion Version:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 ArrayList<Integer> nodes = new ArrayList<Integer>(); 12 public ArrayList<Integer> inorderTraversal(TreeNode root) { 13 inorderTraversal_recursion(root); 14 return nodes; 15 } 16 public void inorderTraversal_recursion(TreeNode root){ 17 if(root==null) 18 return; 19 inorderTraversal_recursion(root.left); 20 nodes.add(root.val); 21 inorderTraversal_recursion(root.right); 22 } 23 24 }
Iterative version:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public ArrayList<Integer> inorderTraversal(TreeNode root) { 12 // the nodes is used to store the result 13 ArrayList<Integer> nodes = new ArrayList<Integer>(); 14 if (root == null) 15 return nodes; 16 Stack<TreeNode> stack = new Stack<TreeNode>(); 17 TreeNode node = root; 18 // note in the begin of the loop, stack is empty, 19 // so we need node != null to make sure the while-loop 20 // can be executed. 21 while (node != null || !stack.isEmpty()) { 22 // if the node is not null, 23 // we should get the left child 24 if (node != null) { 25 stack.push(node); 26 node = node.left; 27 } 28 // if the node is null 29 // i.e. reach the situation that the parent 30 // don't have left child. 31 // we should pop the top of the stack, 32 // and do the operation on the right child. 33 else { 34 node = stack.pop(); 35 nodes.add(node.val); 36 node = node.right; 37 } 38 } 39 return nodes; 40 } 41 }