zoukankan      html  css  js  c++  java
  • Java数组实现顺序存储二叉树,进行前中后序遍历

    /** 用数组实现顺序存储完全二叉树,并进行前序遍历中序遍历后序遍历
     *         1
     *       /  
     *      2    3
     *     /   /
     *    4  5 6
     */
    public class ArrayBinaryTreeDemo {
        public static void main(String[] args) {
            int[] tree = {1, 2, 3, 4, 5, 6};
            ArrayBinaryTree arrayBinaryTree = new ArrayBinaryTree(tree);
            arrayBinaryTree.preOrder();   // 1 2 4 5 3 6
            arrayBinaryTree.infixOrder(); // 4 2 5 1 6 3
            arrayBinaryTree.postOrder();  // 4 5 2 6 3 1
        }
    }
    
    class ArrayBinaryTree {
        private int[] arr;
    
        public ArrayBinaryTree(int[] arr) {
            this.arr = arr;
        }
    
        /**
         * 先序遍历
         */
        public void preOrder() {
            if (arr == null || arr.length == 0) {
                System.out.println("树为空!");
                return;
            }
            preOrder(0);
            System.out.println();
        }
    
        /**
         * 中序遍历
         */
        public void infixOrder() {
            if (arr == null || arr.length == 0) {
                System.out.println("树为空!");
                return;
            }
            infixOrder(0);
            System.out.println();
        }
    
        /**
         * 后序遍历
         */
        public void postOrder() {
            if (arr == null || arr.length == 0) {
                System.out.println("树为空!");
                return;
            }
            postOrder(0);
            System.out.println();
        }
    
        private void infixOrder(int index) {
            int left = index * 2 + 1; // 左子节点index
            if (left < arr.length) infixOrder(left);
            System.out.print(arr[index] + " ");
            int right = index * 2 + 2; // 右子节点index
            if (right < arr.length) infixOrder(right);
        }
    
        private void postOrder(int index) {
            int left = index * 2 + 1;
            if (left < arr.length) postOrder(left);
            int right = index * 2 + 2;
            if (right < arr.length) postOrder(right);
            System.out.print(arr[index] + " ");
        }
    
        private void preOrder(int index) {
            System.out.print(arr[index] + " ");
            int left = index * 2 + 1;
            if (left < arr.length) {
                preOrder(left);
            }
            int right = index * 2 + 2;
            if (right < arr.length) {
                preOrder(right);
            }
        }
    }
  • 相关阅读:
    Mongo 应用查询
    Rocket MQ 问题排查命令
    阿里云部署杂记-节约时间
    linux shell 杂
    垃圾回收算法学习
    Hbase数据读写流程
    TCP 协议相关
    Netty
    ELK
    MiniGUI
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13309089.html
Copyright © 2011-2022 走看看