您的位置:首页 > 其它

二叉树的几种遍历方法,包括递归和迭代

2015-12-29 19:05 507 查看
由于要找工作了复习下二叉树。

public class BinaryTreeTraversal

{

public class TreeNode
{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}

/*
* 二叉树三种遍历的方法:
* 递归前序遍历
*/
public void  pre(TreeNode root)
{
if(root==null)
return ;
System.out.println(root.val);
pre(root.left);
pre(root.right);
}
/*
* 二叉树三种遍历的方法:
* 递归中序遍历
*/
public void  mid(TreeNode root)
{
if(root==null)
return ;
mid(root.left);
System.out.println(root.val);
mid(root.right);
}
/*
* 二叉树三种遍历的方法:
* 递归后续遍历
*/
public void  pos(TreeNode root)
{
if(root==null)
return ;
pos(root.left);
pos(root.right);
System.out.println(root.val);
}

/*
* 二叉树三种遍历的方法:
* 迭代前序遍历
*/
public void itaPre(TreeNode root)
{
Stack<TreeNode> stack=new Stack<TreeNode>();
TreeNode cur=root;
while(!stack.isEmpty()||cur!=null)
{
if(cur!=null)
{
System.out.println(cur.val);
stack.push(cur);
cur=cur.left;
}
else
{
cur=stack.pop();
cur=cur.right;
}
}
}
/*
* 二叉树三种遍历的方法:
* 迭代中序遍历
*/
public void itaMid(TreeNode root)
{
Stack<TreeNode> stack=new Stack<TreeNode>();
TreeNode cur=root;
while(!stack.isEmpty()||cur!=null)
{
if(cur!=null)
{
stack.push(cur);
cur=cur.left;
}
else
{
cur=stack.pop();
System.out.println(cur.val);
cur=cur.right;
}
}
}

/*
* 二叉树三种遍历的方法:
* 迭代后序遍历
*/
public void itaPos(TreeNode root)
{
Stack<TreeNode> stack=new Stack<TreeNode>();
TreeNode cur=root;
TreeNode pre=null;
while(!stack.isEmpty()||cur!=null)
{
while(cur!=null)
{
stack.push(cur);
cur=cur.left;
}
cur=stack.peek();
if(cur.right==null||cur.right==pre)
{
System.out.println(cur.val);
pre=cur;
stack.pop();
cur=null;
}else
{
cur=cur.right;
}
}
}

/*
* 二叉树三种遍历的方法:
* 层次遍历
* 思路:首先将root压入队列中,如果队列不为null那么出队列输出,同时判断cur左右结点是否为null不为空进队列;
* 循环,那么下一个出队列的讲是cur压入队列的那个值:
*/
public void  Level(TreeNode root)
{
Queue<TreeNode> queue=new LinkedList<TreeNode>();
TreeNode cur=null;
queue.add(root);
while(!queue.isEmpty())
{
cur=queue.poll();
System.out.println(cur.val);
if(cur!=null)
{
if(cur.left!=null)
queue.add(cur.left);
if(cur.right!=null)
queue.add(cur.right);
}
}
}

@Test
public void test()
{
TreeNode root=new TreeNode(0);
TreeNode n1=new TreeNode(1);
TreeNode n2=new TreeNode(2);
TreeNode n3=new TreeNode(3);
TreeNode n4=new TreeNode(4);
TreeNode n5=new TreeNode(5);
TreeNode n6=new TreeNode(6);
root.left=n1;
root.right=n2;
n1.left=n3;
n1.right=n4;
n2.left=n5;
n2.right=n6;
Level(root);
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: