105. 從前序與中序遍歷序列構造二叉樹

105. 從前序與中序遍歷序列構造二叉樹 - 力扣(LeetCode) (leetcode-cn.com)

public class BuildTree {

????static HashMapmap =new HashMap<>();//標記中序遍歷

? ? static int[]preorder;//保留的先序遍歷

????public TreeNodebuildTree(int[] preorder, int[] inorder) {

????????????if(preorder.length==0||inorder.length==0)

????????????????????return null;

? ? ? ????? this.preorder = preorder;

? ? ? ????? for (int i =0; i < inorder.length; i++) {

????????????????map.put(inorder[i], i);

? ? ? ? ????}

????????????return recursive(0,0,inorder.length-1);

? ? }

????/**

? ? * @param pre_root_idx? 先序遍歷的索引(當前根節點)

? ? * @param in_left_idx? 中序遍歷的索引(當前二叉樹在中序遍歷中的左邊界)

? ? * @param in_right_idx 中序遍歷的索引(當前二叉樹在中序遍歷中的右邊界)

????*/

? ? public static TreeNoderecursive(int pre_root_idx, int in_left_idx, int in_right_idx) {

????????if(in_left_idx>in_right_idx)

????????????return null;

? ? ? ? //獲取當前根節點

? ? ? ? TreeNode root =new TreeNode(preorder[pre_root_idx]);

? ? ? ? // 在中序中獲當前根的索引

? ? ? ? int idx =map.get(preorder[pre_root_idx]);

? ? ? ? //當前左子樹的根節點就是前序遍歷第一個,就是pre_root_idx+1,左邊邊界就是in_left_idx,右邊邊界是當前根的索引-1

? ? ? ? root.left =recursive(pre_root_idx+1,in_left_idx,idx-1);

? ? ? ? //當前右子樹的根,就是右子樹(前序遍歷)的第一個,就是當前根節點+當前左子樹的數量

? ? ? ? // pre_root_idx 當前的根? 左子樹的長度 = 左子樹的左邊-右邊 (idx-1 - in_left_idx +1) 。最后+1就是右子樹的根了

? ? ? ? root.right =recursive(pre_root_idx + (idx-1 - in_left_idx +1)? +1, idx +1, in_right_idx);

? ? ? ? return root;

? ? }

}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容