思路一:
经典的递归算法
/**
* 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>list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root==null){
return list;
}
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
return list;
}
}
思路二:
迭代算法
/**
* 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>list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
TreeNode rot = root;
Stack<TreeNode> stk = new Stack<TreeNode>();
stk.push(root);
while(!stk.empty()){
while(root.left!=null){
root=root.left;
stk.push(root);
}
list.add(stk.peek().val);
root = stk.pop().right;
stk.push(root);
//System.out.println(root.val);
}
return list;
}
}