标签:style blog color for io new
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 12 public List<Integer> inorderTraversal(TreeNode root) { 13 ArrayList<Integer> arr=new ArrayList<Integer>(); 14 if(root==null) return arr; 15 inorder(root,arr); 16 return (List)arr; 17 18 19 } 20 public void inorder(TreeNode root,ArrayList<Integer> arr) { 21 if(root!=null) 22 { 23 inorder(root.left,arr); 24 arr.add(root.val); 25 inorder(root.right,arr); 26 } 27 28 29 30 } 31 }
2。非递归
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> inorderTraversal(TreeNode root) { ArrayList<Integer> arr=new ArrayList<Integer>(); if(root==null) return arr; Stack<TreeNode> s=new Stack<TreeNode>(); TreeNode t=root; while(!s.isEmpty()||t!=null) { while(t!=null) { s.push(t); t=t.left; } if(s!=null) { t=s.pop(); arr.add(t.val); t=t.right; } } return arr; } }
标签:style blog color for io new
原文地址:http://www.cnblogs.com/hansongjiang/p/3823052.html