/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer> ();
if (root==null) return res;
Stack<TreeNode> stack = new Stack<TreeNode> ();
stack.push(root);
TreeNode current = root.left;
while (!stack.isEmpty() || current!=null) {
if (current!=null) {
stack.push(current);
current = current.left;
} else {
current = stack.peek();
res.add(current.val);
stack.pop();
current = current.right;
}
}
return res;
}
}
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer> ();
inorder(root, res);
return res;
}
public void inorder(TreeNode root, ArrayList<Integer> res) {
if (root==null) return;
inorder(root.left, res);
res.add(root.val);
inorder(root.right, res);
}
}
1. Stack.
回复删除2. 先放root,再放left child直到没有left了.
3. stack最上面的点放到res里,取出该点,再对该点的right child操作.
Recursive
回复删除