输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- class Solution {
- public TreeNode buildTree(int[] preorder, int[] inorder) {
- return build(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
- }
- public TreeNode build(int[] preorder,int preStart,int preEnd, int[] inorder,int inStart,int inEnd){
- if(preStart > preEnd){
- return null;
- }
- int rootval = preorder[preStart];
- int index = 0;
- for(int i = inStart;i <= inEnd;i++){
- if(inorder[i] == rootval){
- index = i;
- break;
- }
- }
- int leftLength = index - inStart;
- TreeNode root = new TreeNode(rootval);
- root.left = build(preorder,preStart+1,preStart + leftLength,inorder,inStart,inStart+leftLength-1);
- root.right = build(preorder,preStart+leftLength+1,preEnd,inorder,inStart+leftLength+1,inEnd);
- return root;
- }
- }
执行用时:3 ms, 在所有 Java 提交中击败了39.18%的用户
内存消耗:40.8 MB, 在所有 Java 提交中击败了80.68%的用户
通过测试用例:203 / 203