溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何重建python二叉樹

發(fā)布時間:2021-12-13 15:25:57 來源:億速云 閱讀:128 作者:柒染 欄目:大數(shù)據(jù)

如何重建python二叉樹,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

題目描述

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

思路

前序遍歷的第一個值為根節(jié)點(diǎn)的值,使用這個值將中序遍歷結(jié)果分成兩部分,左部分為樹的左子樹中序遍歷結(jié)果,右部分為樹的右子樹中序遍歷的結(jié)果,遞歸地去分別構(gòu)建它的左右子樹。

代碼實(shí)現(xiàn)

package Tree;
import java.util.HashMap;
/** * 重建二叉樹 * 輸入某二叉樹的前序遍歷和中序遍歷的結(jié)果,請重建出該二叉樹。假設(shè)輸入的前序遍歷和中序遍歷的結(jié)果中都不含重復(fù)的數(shù)字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹并返回。 */public class Solution54 {    private HashMap<Integer, Integer> inOrderNumsIdx = new HashMap<>(); // 緩存中序遍歷數(shù)組的每個值對應(yīng)的索引
   public TreeNode reConstructBinaryTree(int[] pre, int[] in) {        for (int i = 0; i < in.length; i++) {            inOrderNumsIdx.put(in[i], i);        }        return reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);    }
   private TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int[] in, int inL, int inR) {        if (preL == preR) return new TreeNode(pre[preL]);        if (preL > preR || inL > inR) return null;        // 創(chuàng)建當(dāng)前根節(jié)點(diǎn),并為根節(jié)點(diǎn)賦值        TreeNode root = new TreeNode(pre[preL]);        int inIdx = inOrderNumsIdx.get(root.val);        int leftTreeSize = inIdx - inL;        // 構(gòu)建左子樹        root.left = reConstructBinaryTree(pre, preL + 1, preL + leftTreeSize, in, inL, inL + leftTreeSize - 1);        // 構(gòu)建右子樹        root.right = reConstructBinaryTree(pre, preL + leftTreeSize + 1, preR, in, inL + leftTreeSize + 1, inR);        return root;    }
   public class TreeNode {        int val;        TreeNode left;        TreeNode right;
       TreeNode(int x) {            val = x;        }    }}

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI