给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,3,2]
1 //迭代算法 2 class Solution { 3 public List<Integer> inorderTraversal(TreeNode root) { 4 List<Integer> list = new ArrayList<Integer>(); 5 if(root==null)return list; 6 Stack<TreeNode> stack = new Stack<TreeNode>(); 7 stack.push(root); 8 TreeNode cur = root.left; 9 while(cur!=null||!stack.empty()){ 10 while(cur!=null){ 11 stack.push(cur); 12 cur=cur.left; 13 } 14 TreeNode tmpnode = stack.pop(); 15 list.add(tmpnode.val); 16 cur = tmpnode.right; 17 } 18 return list; 19 } 20 } 21 22 23 //递归算法 24 class Solution { 25 public List<Integer> inorderTraversal(TreeNode root) { 26 List<Integer> list = new ArrayList<Integer>(); 27 if(root==null)return list; 28 inorder(root,list); 29 return list; 30 } 31 public void inorder(TreeNode node,List<Integer> list){ 32 if(node.left!=null)inorder(node.left,list); 33 list.add(node.val); 34 if(node.right!=null)inorder(node.right,list); 35 } 36 }