1. 程式人生 > >劍指offer(四)之 重建二叉樹

劍指offer(四)之 重建二叉樹

題目:

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

思路:

前序遍歷: 根左右
中序遍歷:左根右
根據先序遍歷就能獲得根。
中序遍歷依據根可以把樹一分為二,根的左子樹必定在其左邊,右子樹必定在其右邊。遞迴進去就解決了

程式碼:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
     int[] pre;
    int[] in;
    int index = 0;
    public TreeNode find(int l ,int r){

        if(index >= pre.length  )
            return null;
        TreeNode node = new TreeNode(pre[index++]);
        if(l == r)
            return node;
        int getId = findByIn(node.val,l,r);
        if(getId == -1)
            return node;
        if(getId > l ){
            node.left = find( l,getId-1 );
        }
        if(getId < r ){
            node.right = find(getId+1,r );
        }
        return node;
    }

    private int findByIn( int i ,int l, int r) {
        for (int j = l; j <= r; j++) {
            if (in[j] == i) {
                return j;
            }
        }
        return -1;
    }

    public TreeNode reConstructBinaryTree(int [] pre, int [] in) {
        int n = pre.length;
        this.pre = pre;
        this.in = in;
        return find(0,n-1);
    }
}