中序遍历
1.递归
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: Inorder in ArrayList which contains node values. */ public ArrayList<Integer> inorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> result = new ArrayList<Integer>(); traverse(root, result); return result; } private void traverse(TreeNode root, ArrayList<Integer> result) { if (root == null) { return; } traverse(root.left, result); result.add(root.val); traverse(root.right, result); } }
与前序遍历区别:改变顺序而已
2.分治,两处错误
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: Inorder in ArrayList which contains node values. */ public ArrayList<Integer> inorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> result = new ArrayList<Integer>(); if (root == null) { return result; } ArrayList<Integer> left = inorderTraversal(root.left); ArrayList<Integer> right = inorderTraversal(root.right); result.addAll(left); result.add(root.val);//忘记root.val,写成root result.addAll(right); return result; //忘记 } }
3.非递归的方法,使用栈
先从根节点把所以左边的点入栈,
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: Inorder in ArrayList which contains node values. */ public ArrayList<Integer> inorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> result = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode curt = root; while (curt != null || !stack.empty()) { while (curt != null) { stack.add(curt); //stack.push(curt);这两个有啥区别? curt = curt.left; } //curt = stack.peek(); //stack.pop(); curt = stack.pop();//这样也行 result.add(curt.val); curt = curt.right; } return result; } }