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

来源:互联网 发布:安能 淘宝 编辑:程序博客网 时间:2024/05/26 16:01

由于要找工作了复习下二叉树。
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);       }    }}@Testpublic 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);}

}

0 0
原创粉丝点击