1. 程式人生 > >劍指offer--重建二叉樹

劍指offer--重建二叉樹

lag node rec 劍指offer == str eno truct 個數字

題目 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
思路 先畫圖 分析在二叉樹的前序遍歷序列中,第一個數字總是樹的根節點的值。但在中序遍歷中,根節點的值在序列的中間,左子樹的節點的值位於根節點的值得左邊,而右子樹的節點的值位於根節點的值的右邊。
自己寫的low代碼

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
             if(pre==null||pre.length==0||in ==null||in.length==0) {
                return  null;
            }
            TreeNode root = new TreeNode(pre[0]);
            int flag = -1;
            for(int i=0;i<in.length;i++) {
                if(in[i]==root.val) {
                    flag = i;
                    break;
                }
            }
            int[] preLeft = new int[flag];
            int[] preRight = new int[in.length-flag-1];
            int[] inLeft = new int[flag];
            int[] inRight =new int[in.length-flag -1];
        
            for(int i=1;i<=flag;i++) {
                preLeft[i-1]=pre[i];
            }
            for(int i=flag+1;i<in.length;i++) {
                preRight[i-flag-1]=pre[i];
            }
            for(int i=0;i<flag;i++) {
                inLeft[i]=in[i];
            }
            for(int i=flag+1;i<in.length;i++) {
                inRight[i-flag-1]=in[i];
            }
           root.left =  reConstructBinaryTree(preLeft,inLeft);
            root.right =reConstructBinaryTree(preRight,inRight);
            return root;
        }
   
}

劍指offer--重建二叉樹