对于二叉树的前序,中序,后序遍历,相信利用递归来做我们已经非常熟悉了,而如何非递归进行前序,中序,后序呢?
一、前序
递归实现:
public void preOrder_recursive(TreeNode root){
if(root==null){
System.out.print("null ");
return;
}
System.out.print(root.val+" ");
preOrder_recursive(root.left);
preOrder_recursive(root.right);
}
非递归实现:
//非递归用栈
public void preOrder(TreeNode root){
Stack<TreeNode> s=new Stack<>();
TreeNode cur=root;
while(cur!=null||!s.empty()){
while(cur!=null){
s.push(cur);
System.out.print(cur.val+" ");
cur=cur.left;
}
TreeNode top=s.pop();
cur=top.right;
}
}
二、中序
递归实现:
public void Inorder_recursive(TreeNode root){
if(root==null){
return ;
}
Inorder_recursive(root.left);
System.out.print(root.val+" ");
Inorder_recursive(root.right);
}
非递归实现:
public void Inorder(TreeNode root){
Stack<TreeNode> s=new Stack<>();
TreeNode cur=root;
while(cur!=null||!s.empty()){
while(cur!=null){
s.push(cur);
cur=cur.left;
}
TreeNode top=s.pop();
System.out.print(top.val+" ");
cur=top.right;
}
}
三、后序
递归:
public void PostOrder_recursive(TreeNode root){
if(root==null){
return ;
}
PostOrder_recursive(root.left);
PostOrder_recursive(root.right);
System.out.print(root.val+" ");
}
非递归:
public void PostOrder(TreeNode root){
Stack<TreeNode> s=new Stack<>();
TreeNode cur=root;
TreeNode pre=root;
while(cur!=null||!s.empty()){
//一直找,找到最左边
while(cur!=null){
s.push(cur);
cur=cur.left;
}
TreeNode top=s.peek();
cur=top.right;
if(cur==null||cur==pre){
System.out.print(top.val+" ");
pre=s.pop();
cur=null;
}
}
}