【每日一題】【遞迴】2021年12月24日-105. 從前序與中序遍歷序列構造二叉樹
阿新 • • 發佈:2021-12-25
給定一棵樹的前序遍歷 preorder 與中序遍歷 inorder。請構造二叉樹並返回其根節點。
答案:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * }*/ class Solution { private Map<Integer, Integer> map; public TreeNode build(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) { //注意迴圈條件,先序的左邊小於右邊?--0個元素時,說明已經為空 if(preStart > preEnd) { return null; } int in_root = map.get(preorder[preStart]);int left_size = in_root - inStart; TreeNode root = new TreeNode(inorder[in_root]); root.left = build(preorder, preStart + 1, preStart + left_size, inorder, inStart, in_root - 1); //注意是preEnd,而不是in_root root.right = build(preorder, preStart + left_size + 1, preEnd, inorder, in_root + 1, inEnd);return root; } public TreeNode buildTree(int[] preorder, int[] inorder) { map = new HashMap<>(); for(int i = 0; i < inorder.length; i++) { map.put(inorder[i], i); } return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); } }
本文來自部落格園,作者:劉金輝,轉載請註明原文連結:https://www.cnblogs.com/liujinhui/p/15729432.html