从二叉树的前序和中序得到后续遍历算法

public class ConvertToPost {
                private char[] preArr;
                private char[] inArr;
                private char[] postArr;

                public ConvertToPost(char[] preArr, char[] inArr) {
                        this.preArr = preArr;
                        this.inArr = inArr;
                }

                //
                public char[] getpostArr() throws ArrayWrongException {
                        Node Root = toBTree(0, preArr.length - 1, 0, inArr.length - 1);
                        if (preArr.length != inArr.length)
                                throw new ArrayWrongException(
                                                "the length of the two array is not equal!");
                        postArr = new char[preArr.length];
                        postOrder(Root);
                        return postArr;
                }

                private Node toBTree(int preL, int preR, int inL, int inR)
                                throws ArrayWrongException {
                        Node root = new Node(preArr[preL]);
                        int rootIninArr = -1;
                        int i = -1;
                        for (i = inL; i <= inR; i++)
                                if (inArr[i] == root.key) {
                                        rootIninArr = i;
                                        break;
                                }
                        if (i == inR + 1)
                                throw new ArrayWrongException(
                                                "the two array cant convert to a binary tree!");
                        int leftLen = rootIninArr - inL;
                        int rightLen = inR - rootIninArr;
                        if (leftLen != 0)
                                root.left = toBTree(preL + 1, preL + leftLen, inL,
                                                rootIninArr - 1);
                        if (rightLen != 0)
                                root.right = toBTree(preL + leftLen + 1, preR, rootIninArr + 1,
                                                inR);
                        return root;
                }

                private void postOrder(Node node) {
                        if (node != null) {
                                postOrder(node.left);
                                postOrder(node.right);
                                for (int i = 0; i < postArr.length; i++)
                                        if ((int) postArr[i] == 0) {
                                                postArr[i] = node.key;
                                                break;
                                        }
                        }
                }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值