题目:
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题过程①:
递归
思路来源于LeetCode用户:Ant
/**
* 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) {
int n = preorder.length;
if(n==0) return null;
int rootVal = preorder[0], rootIndex = 0;
for(int i=0;i<n;i++){
if(inorder[i]==rootVal){
rootIndex=i; // 找根节点在中序遍历中的索引
break;
}
}
TreeNode root = new TreeNode(rootVal);
root.left = buildTree(Arrays.copyOfRange(preorder, 1, 1+rootIndex), Arrays.copyOfRange(inorder, 0, rootIndex));
root.right = buildTree(Arrays.copyOfRange(preorder,1+rootIndex, n), Arrays.copyOfRange(inorder, 1+rootIndex,n));
return root;
}
}
执行结果①:
解题过程②:
尚待完善