您的位置:首页 > 编程语言 > Java开发

二叉树非递归遍历Java实现

2017-06-30 13:59 417 查看
二叉树的前序、中序和后序遍历可以采用递归和非递归的方法实现,递归的方法逻辑简单清晰,易于理解,但递归的方法需要使用额外的栈空间,运行效率较低。而非递归的方法则效率较高。

维基百科上有递归和非递归二叉树三种遍历实现的伪代码,https://en.wikipedia.org/wiki/Tree_traversal#In-order_2

下面是相应的Java实现:

前序遍历(非递归实现):

public static void preOrder(TreeNode x)
{
System.out.println();
if(x!=null)
{
LinkedList<TreeNode> stack=new LinkedList<TreeNode>();

stack.addLast(x);
while(!stack.isEmpty())
{
TreeNode temp=stack.removeLast();
System.out.print(temp.val+" ");

if(temp.rchild!=null)
{
stack.addLast(temp.rchild);
}

if(temp.lchild!=null)
{
stack.addLast(temp.lchild);
}

}
System.out.println();
}
}

中序遍历(非递归实现):

public static void inOrder(TreeNode x)
{
System.out.println();
if(x!=null)
{
LinkedList<TreeNode> stack=new LinkedList<TreeNode>();

while(!stack.isEmpty()||x!=null)
{
if(x!=null)
{
stack.addLast(x);
x=x.lchild;
}
else
{
x=stack.removeLast();
System.out.print(x.val+" ");
x=x.rchild;
}
}
System.out.println();
}
}


后序遍历(非递归实现):

public static void postOrderII(TreeNode x)
{
LinkedList<TreeNode> stack=new LinkedList<TreeNode>();
TreeNode lastNodeVistited=null;
while(!stack.isEmpty()||x!=null)
{
if(x!=null)
{
stack.addLast(x);
x=x.lchild;
}
else
{
TreeNode top=stack.getLast();
if(top.rchild!=null&&lastNodeVistited!=top.rchild)
{
x=top.rchild;
}
else
{
System.out.print(top.val+" ");
lastNodeVistited=stack.removeLast();
}
}
}
System.out.println();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: