public List<Integer> preorderTraversal(TreeNode root) {//前序
List<Integer> result = new ArrayList<>();
Stack<TreeNode> tmp = new Stack<>();
if(root != null) tmp.push(root);
TreeNode cur = null;
while(!tmp.isEmpty()){
cur = tmp.pop();
if(cur!=null){
if(cur.right!=null) tmp.push(cur.right);
if(cur.left!=null) tmp.push(cur.left);
tmp.push(cur);
tmp.push(null); // 中节点访问过,但是还没有处理,加入空节点做为标记。
} else{// 只有遇到空节点的时候,才将下一个节点放进结果集
cur = tmp.pop();// 重新取出栈中元素
result.add(cur.val);
}
}
return result;
}
public List<Integer> preorderTraversal(TreeNode root) { //中序
List<Integer> result = new ArrayList<>();
Stack<TreeNode> tmp = new Stack<>();
if(root != null) tmp.push(root);
TreeNode cur = null;
while(!tmp.isEmpty()){
cur = tmp.pop();
if(cur!=null){
if(cur.right!=null) tmp.push(cur.right);
tmp.push(cur);
tmp.push(null);
if(cur.left!=null) tmp.push(cur.left);
}
else{
cur = tmp.pop();
result.add(cur.val);
}
}
return result;
}
public List<Integer> preorderTraversal(TreeNode root) { //后序
List<Integer> result = new ArrayList<>();
Stack<TreeNode> tmp = new Stack<>();
if(root != null) tmp.push(root);
TreeNode cur = null;
while(!tmp.isEmpty()){
cur = tmp.pop();
if(cur!=null){
tmp.push(cur);
tmp.push(null);
if(cur.right!=null) tmp.push(cur.right);
if(cur.left!=null) tmp.push(cur.left);
}
else{
cur = tmp.pop();
result.add(cur.val);
}
}
return result;
}