先序
public void xianxu(TreeNode root) {
if(root == null) return ;
stack.push(root);
while(!stack.isEmpty()){
TreeNode tmp =stack.pop();
System.out.print(tmp.val+" ");
if(tmp.right!=null) stack.push(tmp.right);
if(tmp.left!=null) stack.push(tmp.left);
}
}
中序
public static void zhongxu(TreeNode root){
TreeNode cur =root;
stack.push(cur);
cur = cur.left;
while(!stack.isEmpty() || cur !=null){
if(cur!= null){
stack.push(cur);
cur =cur.left;
}else{
cur =stack.pop();
System.out.print(cur.val+" ");
cur = cur.right;
}
}
}
后序
public static void houxu(TreeNode root){
if(root == null)return ;
TreeNode cur =root;
stack1.push(cur);
while(!stack1.isEmpty()){
cur = stack1.pop();
stack2.push(cur);
if(cur.left != null){
stack1.push(cur.left);
}
if(cur.right != null){
stack1.push(cur.right);
}
}
while(!stack2.isEmpty()){
cur =stack2.pop();
System.out.print(cur.val+" ");
}
}