劍指offer-重建二叉樹


題目描述:

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

public class Test {
    /*
     * 二叉樹節點類
     */
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) {
            this.val = x;
        }
    }
    /*
     * 給定二叉樹的前序遍歷和中序遍歷,重構二叉樹。假設前序遍歷和中序遍歷都沒有重復的數
     */
    
    /**
     * 
     * @param pre  前序遍歷
     * @param in    中序遍歷
     * @return        二叉樹根節點
     */
     public TreeNode reConstructBinaryTree(int[] pre,int[] in) {
         /*
          * 輸入合法性判斷, 不能為空,先序和后序長度要一致
          */
         if(pre == null || in == null || pre.length != in.length) 
             return null;
         
         return construct(pre, 0, pre.length-1, in, 0, in.length-1);
     }
     /**
      * 
      * @param pre    前序遍歷
      * @param ps    前序遍歷的開始位置
      * @param pe    前序遍歷的結束位置
      * @param in    中序遍歷
      * @param is    中序遍歷的開始位置
      * @param ie    中序遍歷的結束位置
      * @return        數的根節點
      */
     private TreeNode construct(int[] pre, int ps, int pe, int[] in, int is, int ie) {
         if(ps > pe) return null;
         
         // 取前序遍歷的第一個數字就是根節點
         int value = pre[ps];
         // 在中序遍歷中中尋找根節點
         int index =is;
         while(index <= ie && value != in[index]) {
             index ++;
         }
         // 如果在整個中序遍歷的數組中沒有找到,說明輸入的參數是不合法的,拋出異常 
         if(index > ie) 
             throw new RuntimeException("Invalid Iuput!");
         
         // 創建當前根節點,並為根節點賦值
         TreeNode node = new TreeNode(value);
         // 遞歸調用構建當前節點的左子樹 
         node.left = construct(pre, ps+1, ps+index-is, in, is, index-1);
         // 遞歸調用構建當前節點的右子樹
         node.right = construct(pre, ps+index-is+1, pe, in, index+1, ie);
         
         return node;
    }
     
     
     private void printTree(TreeNode root) {
         if(root != null) {
             printTree(root.left);
             System.out.println(root.val + " ");
             printTree(root.right);
         }
     }
     
     public static void main(String[] args) {
        Test test = new Test();
        int[] pre = {1, 2, 4, 7, 3, 5, 6, 8};
        int[] in = {4, 7, 2, 1, 5, 3, 8, 6};
        TreeNode node = test.reConstructBinaryTree(pre, in);
        test.printTree(node);
        
    }
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM