1.递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List <Integer>res=new ArrayList <Integer>();
helper(root,res);
return res;
}
public List helper(TreeNode root,List<Integer> res){
if (root != null) {
if (root.left != null) {
helper(root.left, res);
}
res.add(root.val);
if (root.right != null) {
helper(root.right, res);
}
}
return res;
}
}
2.栈消除递归
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res= new ArrayList<Integer>();
Stack<TreeNode> st= new Stack<TreeNode>();
TreeNode curr=root;//
while(curr!=null||!st.isEmpty()){
while(curr!=null){
st.push(curr);
curr=curr.left;
}//遍历到底,栈顶即树分支底部
curr=st.pop();
res.add(curr.val);
curr=curr.right;//从下往上判断可否要进入右分支比例
}
return res;
}
}