Steam 平臺線上人數再創新高,峰值突破 2640 萬人
阿新 • • 發佈:2021-02-10
題目描述
根據一棵樹的前序遍歷與中序遍歷構造二叉樹。
注意:
你可以假設樹中沒有重複的元素。
例如,給出
前序遍歷 preorder = [3,9,20,15,7]
中序遍歷 inorder = [9,3,15,20,7]
返回如下的二叉樹:
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
思路
迭代,用前序確定頭結點,用中序確定左右子樹
/**
* 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> indexMap;
public TreeNode buildTree(int[] preorder, int[] inorder) {
indexMap = new HashMap<>();
for(int i = 0;i < inorder.length;++i){
indexMap.put(inorder[i],i);
}
return helpBuildTree( preorder,inorder,0,preorder.length-1,0,inorder.length-1);
}
public TreeNode helpBuildTree(int[] preorder,int[] inorder,int preLeft,int preRight,int inLeft,int inRight){
if(inLeft > inRight){
return null;
}
int root = preorder[preLeft];
int rootIndex = indexMap.get(root);
TreeNode node = new TreeNode(root);
node.left = helpBuildTree(preorder,inorder,preLeft+1,preLeft+rootIndex-inLeft,inLeft,rootIndex-1);
node.right = helpBuildTree(preorder,inorder,preLeft+rootIndex-inLeft+1,preRight,rootIndex+1,inRight);
return node;
}
}