樹的遍歷

算法僞碼(已知樹的前序s1,中序遍歷s2,求後序遍歷s3)

build(int n,int z,int[] s1,int s2[],int[] s3)
if n<=0
// 當前數組的長度爲0時退出當前遞歸
    return;

s3[n+z-1] = s1[0]
//前序的第一位數字,既是後序的當前子樹長度+偏移量 位的數字

 int p = searchFirst(lxr, xlr[0]);
//尋找 根節點,在中序中的位置,方便區分左右子樹

build(p, z, s1[1,...p+1], s2[0,1...,p], s3);
// 左子樹的遍歷,左子樹長度爲p,偏移量不變

build(n - p - 1, z + p, s1[p+1,...], s2[p+1,....],s3);
// 右子樹的遍歷,右子樹長度爲n-p-1,偏移量爲當前偏移量與左子樹長度之和

樹的遍歷

public class TestB {

    public static void main(String[] args) {
        TestB t = new TestB();

        int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7 };
        TreeNode tree = new TreeNode();
        build(tree, a, 0);
        int[] xlr = new int[] { 1, 2, 5, 3, 6, 7 };
        int[] lxr = new int[] { 2, 5, 1, 6, 3, 7 };
        int[] lrx = new int[6];
        print(tree);
        System.out.println();
        t.build(6, 0, xlr, lxr, lrx);
        t.out(lrx);
    }

    private static class TreeNode {
        Integer val;
        TreeNode parent;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(Integer val) {
            this.val = val;
        }

        void print() {
            System.out.print(this.val + " ");
        }

        @Override
        public String toString() {
            return "TreeNode [val=" + val + ", parent=" + parent + ", left=" + left + ", right=" + right + "]";
        }
    }

    public static void build(TreeNode tree, int[] a, int num) {

        tree.val = a[0];
        tree.left = new TreeNode(a[1]);
        tree.right = new TreeNode(a[2]);

        tree.left.right = new TreeNode(a[4]);
        tree.right.left = new TreeNode(a[5]);
        tree.right.right = new TreeNode(a[6]);

    }

    public static void print(TreeNode tree) {
        if (tree == null) {
            return;
        }

        print(tree.left);

        print(tree.right);
        tree.print();
    }

    /**
     * 
     * @param n 子樹數組長度
     * @param z 子樹偏移長度
     * @param xlr 前序遍歷子樹
     * @param lxr 中序遍歷子樹
     * @param lrx 後續遍歷子樹
     */
    public void build(int n, int z, int[] xlr, int[] lxr, int[] lrx) {
        if (n <= 0 ) {
            return;
        }
        lrx[n + z - 1] = xlr[0];
        System.out.println(n + " --->  " + z + " --->  " + xlr[0]);
        int p = searchFirst(lxr, xlr[0]);

        // 左子樹的遍歷
        build(p, z, Arrays.copyOfRange(xlr, 1, p + 1), Arrays.copyOfRange(lxr, 0, p), lrx);

        // 右子樹的遍歷
        build(n - p - 1, z + p, Arrays.copyOfRange(xlr, p + 1, xlr.length), Arrays.copyOfRange(lxr, p + 1, lxr.length),lrx);
    }

    public int searchFirst(int[] a, int key) {

        for (int i = 0; i < a.length; i++) {
            if (a[i] == key) {
                return i;
            }
        }
        return -1;
    }

    public void out(int[] a) {
        for (int i : a) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
相關文章
相關標籤/搜索