(劍指offer)重建二叉樹

題目描述:
  輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。

代碼如下:

public class ReConstructBinaryTree {
    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {

        TreeNode root = null;

        if (pre == null || in == null) {
            return null;
        }
        root = constructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
        return root;
    }

    public TreeNode constructBinaryTree(int[] pre, int preStr, int preEnd, int[] in, int inStr, int inEnd) {
        if (preStr > preEnd || inStr > inEnd) {
            return null;    
        }
        // 前序遍歷的第一個結點爲二叉樹的根節點
        TreeNode root = new TreeNode(pre[preStr]);
        // 記錄每次根節點所在位置
        int index = 0;
        for (; index < inEnd; index++) {
            if (in[index] == pre[preStr]) {
                break;
            }
        }
        // 遞歸調用求得根節點的左子樹
        root.left = constructBinaryTree(pre, preStr + 1, preStr + index - inStr, 
                in, inStr, index - 1);
        // 遞歸調用求得根節點的右子樹
        root.right = constructBinaryTree(pre, preStr + index - inStr + 1, preEnd, 
                in, index + 1, inEnd);
        return root;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章