leetcode-105 从前序与中序遍历序列构造二叉树
前序的第一个节点是根节点,然后在中序中找到这个节点的位置,该位置前为左子树,后为右子树。
/**
* 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 preLeft, int preRight, int[] inorder, int inLeft, int inRight){
if (preLeft > preRight) return null;
int i = 0;
TreeNode root = new TreeNode(preorder[preLeft]);
// 查找根节点在中序中的位置
for (i = inLeft; i <= inRight; i++){
if (inorder[i] == preorder[preLeft]){
break;
}
}
// 构建左子树
root.left = buildTree(preorder, preLeft + 1, preLeft + (i - inLeft), inorder, inLeft, i - 1);
// 构建右子树
root.right = buildTree(preorder, preLeft + 1 + (i - inLeft), preRight, inorder, i + 1, inRight);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
TreeNode root = buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
return root;
}
}