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?
Recursive 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 // Start typing your Java solution below 13 // DO NOT write main() function 14 ArrayList<Integer> result = new ArrayList<Integer>(); 15 if(root == null){ 16 return result; 17 } 18 19 if(root.left != null){ 20 result.addAll(inorderTraversal(root.left)); 21 } 22 result.add(root.val); 23 if(root.right != null){ 24 result.addAll(inorderTraversal(root.right)); 25 } 26 return result; 27 } 28 }
Iterative Version
1 public ArrayList<Integer> inorderTraversal(TreeNode root) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 ArrayList<Integer> res = new ArrayList<Integer>(); 5 if(root==null) return res; 6 7 Stack<TreeNode> s = new Stack<TreeNode>(); 8 TreeNode cur = root; 9 while(!s.isEmpty()||cur!=null){ 10 if(cur!=null){ 11 s.push(cur); 12 cur=cur.left; 13 }else{ 14 cur=s.pop(); 15 res.add(cur.val); 16 cur=cur.right; 17 } 18 } 19 return res; 20 }
复杂度:时间O(n),空间O(logn)
Morris 算法见如下链接
http://gongxuns.blogspot.com/2012/12/leetcodebinary-tree-inorder-traversal.html