1、先序遍历
遍历顺序:根左右,利用栈
public void preOrder(TNode root){
if(root==null){
return ;
}
Stack<TNode> s=new Stack<TNode>();
while(!s.empty()||root!=null){
while(root!=null){
print(root.val);
s.push(root);
root=root.left;
}
if(!s.empty()){
root=s.pop();
root=root.right;
}
}
}
2、中序遍历
遍历顺序:左根右,利用栈
public void inOrder(TNode root){
if(root==null){
return ;
}
Stack<TNode> s=new Stack<TNode>();
while(!s.empty()||root!=null){
while(root!=null){
s.push(root);
root=root.left;
}
if(!s.empty()){
root=s.pop();
print(root.val);
root=root.right;
}
}
}
3、后序遍历
遍历顺序:左右根,利用栈,如果左右孩子都访问完了之后就访问根节点,否则将右孩子、左孩子压栈。那么如何判断左右孩子都访问过了呢?可以设一个变量last保存上一次访问的节点.
public void postOrder(TNode root){
if(root==null){
return ;
}
Stack<TNode> s=new Stack<TNode>();
s.push(root);
TNode last=root;
TNode p;
while(!s.empty()){
p=s.top();
if((root.left==null&&root.right==null)||(root.right==null&&last==root.left)||(last==root.right)){//左右孩子节点都访问完了
print(root.val);
last=p;
s.pop();
}else{
if(p.right)
s.push(p.right);
if(p.left)
s.push(p.left);
}
}
}