已知前序和中序遍歷,重建二叉樹

想在牛客網上寫此題目,請點擊此處
題目描述:
  輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
分析:
前序遍歷:根節點 -> 左子樹 -> 右子樹
中序遍歷:左子樹 -> 根節點 -> 右子樹
後序遍歷:左子樹 -> 右子樹 -> 根節點
當我們知道了前序遍歷和中序遍歷之後,我們可通過其遍歷規則,將二叉樹重建:

  1. 確定樹的根節點:前序遍歷的第一個結點就是二叉樹的根節點
  2. 求解樹的左右子樹:找到根節點在中序遍歷中的位置,根節點左邊是二叉樹的左子樹,根節點的右邊時二叉樹的右子樹;如果根節點的左邊或右邊爲空,那麼方向的子樹爲空;如果根節點的左邊和右邊都爲空,那麼該節點時葉子節點。
  3. 對左右子樹分別進行1,2兩個步驟,直至求出完整的二叉樹結構爲止。

在這裏插入圖片描述
代碼如下:

/**
 * 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) {
        // pre:1 2 4 7 3 5 6 8
        // in :4 7 2 1 5 3 8 6
         TreeNode root = reConstructBinaryTree(pre, 0, pre.length-1, in, 0, in.length-1);
        
        return root;
    }
    public TreeNode reConstructBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn){
        if(startPre > endPre || startIn > endIn){
            return null;
        }
        // 根據前序遍歷結果,創建根節點
        TreeNode root  = new TreeNode(pre[startPre]);
        // 根節點爲:1
        // 在中序遍歷的結果中找到根節點,找到其左右結點
        // 中序結果分離:        對應的前序遍歷
        // 左子樹:4 7 2        2 3 7
        // 右子樹:5 3 8 6      3 5 6 8
        for(int i = startIn; i <= endIn; i++){
            if(in[i] == pre[startPre]){
                root.left = reConstructBinaryTree(pre, startPre+1, startPre+i-startIn, in, startIn, i-1);
                root.right = reConstructBinaryTree(pre, i-startIn+startPre+1, endPre, in, i+1, endIn);
            }
        }
        return root;
    }
}

牛客網在線OJ執行結果爲:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章