乐趣区

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);
        }
    }
}
退出移动版