二叉树的先序、中序、后序遍历

* 先序遍历:中->左->右
* 中序遍历:左->中->右
* 后序遍历:左->右->中

方法1:

public class demo1 {

    public static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
        public TreeNode(int data){
            this.val = data;
        }
    }
    public static void threeorders(TreeNode root){
        int[][] arr = new int[3][];
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        List<Integer> list3 = new ArrayList<>();
        preorder(root,list1);
        inorder(root,list2);
        postorder(root,list3);
        arr[0] = new int[list1.size()];
        arr[1] = new int[list2.size()];
        arr[2] = new int[list3.size()];
        System.out.println("先序遍历");
        for(int i = 0; i<list1.size(); i++){
            arr[0][i] = list1.get(i);
            System.out.print(arr[0][i] + " ");
        }
        System.out.println();
        System.out.println("中序遍历");
        for(int i = 0; i<list1.size(); i++){
            arr[1][i] = list2.get(i);
            System.out.print(arr[1][i] + " ");

        }
        System.out.println();
        System.out.println("后续遍历");
        for(int i = 0; i<list1.size(); i++){
            arr[2][i] = list3.get(i);
            System.out.print(arr[2][i] + " ");

        }

//        return arr;
    }

    //中 ->左 ->右
    public static void preorder(TreeNode root, List<Integer> list){
        if(root != null){
            list.add(root.val);
            preorder(root.left,list);
            preorder(root.right,list);
        }
    }

    //左 ->中  ->右
    public static void inorder(TreeNode root, List<Integer> list){
        if(root != null){
            inorder(root.left,list);
            list.add(root.val);
            inorder(root.right,list);
        }
    }

    //左 -> 右 ->中
    public static void postorder(TreeNode root, List<Integer> list){
        if(root != null){
            postorder(root.left,list);
            postorder(root.right,list);
            list.add(root.val);
        }
    }
    public static void main(String[] args) {
        //构建树

        TreeNode head = new TreeNode(1);

        head.left = new TreeNode(2);

        head.right = new TreeNode(3);

        head.left.left = new TreeNode(4);

        head.left.right = new TreeNode(5);

        head.right.left = new TreeNode(6);

        head.right.right = new TreeNode(7);

        threeorders(head);

    }
}

方法2:

public class demo1 {

    public static class Node{
        public int value;

        public Node left;

        public Node right;

        public Node(int data){
            this.value = data;
        }
    }


    public static void main(String[] args){
        //构建树

        Node head = new Node(1);

        head.left = new Node(2);

        head.right = new Node(3);

        head.left.left = new Node(4);

        head.left.right = new Node(5);

        head.right.left = new Node(6);

        head.right.right = new Node(7);
        //为解决最大宽度不在二叉树最后一层,构造子树

        head.left.right.right = new Node(8);
        head.right.left.left = new Node(9);
        head.right.right.right = new Node(10);

        /**
         * 先序
         */
        proOrderUnrecur1(head);

        /**
         * 后序遍历
         */
        posOrderUnrecur1(head);

        /**
         * 中序遍历
         */
        inOrderUnrecur(head);

        /**
         * 二叉树最大宽度
         */
        System.out.println(process(head));
    }
    /**
     * 先序遍历:中->左->右
     * 中序遍历:左->中->右
     * 后序遍历:左->右->中
     */

    //非递归解决二叉树

    /**
     * 先序遍历:先押右后押左边
     * @param head
     */
    public static void proOrderUnrecur1(Node head){
        System.out.println("先序遍历");
        if (head != null){
            Stack<Node> stack = new Stack<>();//定义栈

            stack.add(head);//存入头结点

            while (!stack.isEmpty()){//循环一直到栈内没有数据弹出

                head = stack.pop();//每次弹出一个节点

                System.out.print(head.value + " ");//弹出节点就打印

                if (head.right != null){//右子树不为空

                    stack.push(head.right);//先押入右
                }
                if (head.left != null){//左子树不为空

                    stack.push(head.left);//押入左
                }
            }
        }
        System.out.println();
    }

    /**
     * 后序遍历
     * 先押左后押右:中->右->左,将顺序搜集后逆序打印后序遍历:左->右->中
     */

    public static void posOrderUnrecur1(Node head){

        System.out.println("后序遍历:");

        if (head != null){

            Stack<Node> stack1 = new Stack<>();//用于遍历二叉树使用的栈

            Stack<Node> stack2 = new Stack<>();//用于打印收集打印顺序,逆序打出

            stack1.push(head);//将头结点存入栈1
            while (!stack1.isEmpty()){

                head = stack1.pop();//每次从栈1中弹出一个节点:弹出顺序为中右左

                stack2.push(head);//将弹出的节点存入栈2中

                if (head.left != null){//押入顺序为先押入左,后押入右

                    stack1.push(head.left);
                }
                if (head.right != null){

                    stack1.push(head.right);
                }
            }
            while (!stack2.isEmpty()){
                System.out.print(stack2.pop().value + " ");
            }
        }
        System.out.println();
    }

    /**
     *中序遍历:左->中->右
     * 阶段1:子树整个左边界一次进入栈,如果没有,进入阶段2
     * 阶段2:从栈中弹出节点的右子树,重复阶段1
     *
     */

    public static void inOrderUnrecur(Node head){

        System.out.println("中序遍历:");


        if (head != null){

            Stack<Node> stack = new Stack<>();

            Node cur = head;//栈顶

            while (!stack.isEmpty() || cur != null){//栈为null,cur为null时候停止
                //cur为null说明没有左边界押入。栈为null,说明没有数据弹出打印
                if (cur != null){//阶段1,如果不为空,

                    stack.push(cur);//当前节点进栈

                    cur = cur.left;//cur向左
                }else {//阶段1结束

                    cur = stack.pop();//从栈中弹出一个节点并打印

                    System.out.print(cur.value + " ");

                    cur = cur.right;//并且cur到达右子树头结点位置
                }
            }
        }
        System.out.println();
    }

    /**
     * 二叉树宽度优先遍历:求一个二叉树最大宽度
     * 使用队列
     */

    public static int process(Node head){

        System.out.println("二叉树最大宽度");

        if (head == null){//为null时候返回
            return 0 ;
        }
        //为求得最大宽度在那一层,定义一个层数表
        HashMap<Node, Integer> levelMap = new HashMap<>();

        //如果不为空时候加入队列
        Queue<Node> queue = new LinkedList<>();//双向链表实现

        levelMap.put(head,1);//头结点在第一层

        queue.add(head);//加入头

        int cLevel = 1;//当前遍历到的层

        int cNodes = 0;//统计当前层节点个数

        int max = 0;//记录节点数最多层
        while (!queue.isEmpty()) {//队列不为null

            Node cur = queue.poll();//弹出队列

            int level = levelMap.get(cur);//层数

            if (level == cLevel){//判断现在的层是否还在统计的层上

                cNodes ++;//每循环一次,节点数目+1
            }else {//如果当前层数不是统计的层上,到下一层
//                System.out.println("层数 : " + cLevel + ",节点数目0" + cNodes);
                if (cNodes > max){
                    max = cNodes;//如果获取节点数目比之前统计最大节点数目多,将当前节点数目赋值给最大节点max
                }
                cLevel ++;//层数向下进一层

                cNodes = 1;//节点数目恢复到1
            }

//            System.out.println("Node : " + cur.value + ", 层数 :" + level);//弹出后打印

            //先进左后进右
            if (cur.left != null){

                levelMap.put(cur.left,level + 1);//当前层数+1

                queue.add(cur.left);
            }
            if (cur.right != null){

                levelMap.put(cur.right,level+1);

                queue.add(cur.right);
            }
        }
        //循环结束后单独记录第四层节点
//        System.out.println("层数 : " + cLevel + ",节点数目0" + cNodes);
        max = Math.max(max,cNodes);
        return max;

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值