标签:vat init 题目 val help new int 二叉树 序列
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private HashMap<Integer, Integer> indexMap = new HashMap<>();
private int[] preorder;
private int[] inorder;
public TreeNode buildTree(int[] preorder, int[] inorder) {
for (int i = 0; i < inorder.length; ++i) {
indexMap.put(inorder[i], i);
}
this.preorder=preorder;
this.inorder=inorder;
return buildTreeHelper(0, preorder.length, 0, inorder.length);
}
private TreeNode buildTreeHelper(int preorderL, int preorderR, int inorderL,
int inorderR) {
if (preorderL == preorderR) {
return null;
}
TreeNode root = new TreeNode(preorder[preorderL]);
int rootIdx = indexMap.get(preorder[preorderL]);// 中序遍历中根结点的idx
int leftTreeNodeCnt = rootIdx - inorderL;// 左子树节点数
int inorderSplitIdx = preorderL + 1 + leftTreeNodeCnt;
root.left = buildTreeHelper(preorderL + 1, inorderSplitIdx, inorderL, rootIdx);
root.right = buildTreeHelper(inorderSplitIdx, preorderR, rootIdx + 1, inorderR);
return root;
}
}
[LeetCode]105. 从前序与中序遍历序列构造二叉树(递归)
标签:vat init 题目 val help new int 二叉树 序列
原文地址:https://www.cnblogs.com/coding-gaga/p/12250420.html