//preOrder
ArrayList<Integer> preOrder(TreeNode root) {
Stack<TreeNode>stack=newStack<TreeNode>();
ArrayList<Integer> arrayList =new ArrayList<Integer>();
TreeNode p = root;
while (!stack.empty() || p !=null) {
while (p !=null) { //p上面保存的始终都是最新访问到的节点
arrayList.add(p.val);
stack.push(p);
p = p.left;
}
if (!stack.empty()) {
p =stack.pop();
p = p.right;
}
}
return arrayList;
}
//inorder
ArrayList<Integer> inOrder(TreeNode root) {
Stack<TreeNode>stack=newStack<TreeNode>();
ArrayList<Integer> res =new ArrayList<Integer>();
TreeNode p = root;
while (!stack.empty() || p !=null) {
while (p !=null) {
stack.push(p);
p = p.left;
}
if (!stack.empty()) {
p =stack.pop();
res.add(p.val);
p = p.right;
}
}
return res;
}