重建二叉树
2020-06-28 本文已影响0人
凯玲之恋
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
限制:
0 <= 节点个数 <= 5000
/**
* 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) {
if(preorder == null || inorder == null){
return null;
}
return rebuildBinaryTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
}
private TreeNode rebuildBinaryTree(int[] preorder, int startPre, int endPre, int[] inorder, int startIn, int endIn){
if(startPre > endPre ||startIn > endPre){
return null;
}
TreeNode root = new TreeNode(preorder[startPre]);
for(int i = startIn; i <= endIn; i++){
if(root.val == inorder[i]){
root.left = rebuildBinaryTree(preorder, startPre + 1 , startPre + (i - startIn), inorder, startIn, i - 1);
root.right = rebuildBinaryTree(preorder, startPre + (i - startIn) + 1, endPre, inorder, i + 1, endPre );
break;
}
}
return root;
}
}