• 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);
            }
        }
    }
  • 相关阅读:
    Vue框架之基础知识
    Vue框架之初识
    Django组件之modelformset
    Django之小结
    Django组件之modelform
    Django之form表单详解
    jquery基础知识2
    jQuery基础知识1
    js基础知识4
    js基础知识3
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13309089.html
Copyright © 2020-2023  润新知