java---二叉树的遍历

一、二叉树的遍历方式4种
在这里插入图片描述
1、先序遍历根左右
遍历结果:A-B-D-G-J-P-C-E-H-F-I

2、中序遍历—左根右
遍历结果:D-J-G-P-B-A-H-E-C-I-F

3、后序遍历—左右根
遍历结果:J-P-G-D-B-H-E-I-F-C-A

4、层序遍历—从上到下,从左到右
遍历结果:A-B-C-D-E-F-G-H-I-J-P

二、代码实现

  • 节点信息
class Node{
    String val;
    Node left;
    Node right;

    public Node(String val) {
        this.val = val;
    }
}
  • 创建一颗二叉树
   public static Node build(){
       Node a=new Node("A");
       Node b=new Node("B");
       Node c=new Node("C");
       Node d=new Node("D");
       Node e=new Node("E");
       Node f=new Node("F");
       Node g=new Node("G");
       Node h=new Node("H");
       Node i=new Node("I");
       Node j=new Node("J");
       Node p=new Node("P");
       a.left=b;
       a.right=c;
       b.left=d;
       d.right=g;
       g.left=j;
       g.right=p;
       c.left=e;
       c.right=f;
       e.left=h;
       f.left=i;
       return a;
   }

1、先序遍历

   //先序遍历(“根左右”)
    public static void preOrder(Node root){
       if(root==null){
           return ;
       }
       //打印根节点
        System.out.print(root.val);
       //递归遍历左子树
        preOrder(root.left);
        //递归遍历右子树
        preOrder(root.right);
    }

递归过程:(以根和左子树为例,右子树同理)
在这里插入图片描述

2、中序遍历

//"左根右"
 public static  void inOrder(Node root){
       if(root==null){
           return ;
       }
       //递归遍历左子树
       inOrder(root.left);
       //打印根节点
       System.out.print(root.val);
       //递归遍历右子树
       inOrder(root.right);
   }

3、后序遍历

 //后续遍历---"左右根"
    public static  void postOrder(Node root){
        if(root==null){
            return ;
        }
        //递归遍历左子树
        postOrder(root.left);

        //递归遍历右子树
        postOrder(root.right);
        //打印根节点
        System.out.print(root.val);
    }

4、层序遍历
解题思路:
引入一个队列
将根节点入队
队首元素出队并打印
将出队元素的左子树(非空)入队,右子树(非空)入队

    public static void levelOrder(Node root){
        if(root==null){
            return;
        }
        //引入一个对列
        //Queue是一个接口,要new一个实现接口的实例
        Queue<Node> queue=new LinkedList<>();
        //将根节点入队
        queue.offer(root);
        //只要队列中有元素,就将队首元素出队并打印
        while(true){
           Node cur= queue.poll();

           //队列为空,跳出循环
           if(cur==null){
               break;
           }
           System.out.println(cur.val);
            //将出队元素的左子树入队(非空),右子树入队(非空)
            if(cur.left!=null) {
                queue.offer(cur.left);
            }
            if(cur.right!=null) {
                queue.offer(cur.right);
            }
        }

    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值