递归
/**
* 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> ls = new LinkedList<Integer>();
mid(root,ls);
return ls;
}
public static void mid(TreeNode T,List<Integer> ls){
if(T!=null){
mid(T.left,ls);
ls.add(T.val);
mid(T.right,ls);
}
}
}
递推
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ls = new LinkedList<Integer>();
Stack<TreeNode> s = new Stack<TreeNode>();
TreeNode temp = root;
while(temp!=null||!s.isEmpty()) {
while(temp!=null) {
s.push(temp);
temp = temp.left;
}
temp = s.pop(); //感觉这个是左节点 其实相对的话是中 容易产生错觉
ls.add(temp.val);
temp = temp.right;
}
return ls;
}
}