给定一棵树的前序遍历 preorder
与中序遍历 inorder
。请构造二叉树并返回其根节点。
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0 || inorder.length == 0) {
return null;
}
TreeNode root = new TreeNode(preorder[0]);
for (int i = 0; i < inorder.length; i++) {
if (inorder[i] == preorder[0]) {
int[] preLeft = Arrays.copyOfRange(preorder, 1, i + 1);
int[] preRight = Arrays.copyOfRange(preorder, i + 1, preorder.length);
int[] inLeft = Arrays.copyOfRange(inorder, 0, i);
int[] inRight = Arrays.copyOfRange(inorder, i + 1, inorder.length);
root.left = buildTree(preLeft, inLeft);
root.right = buildTree(preRight, inRight);
break;
}
}
return root;
}
}
根据一棵树的中序遍历与后序遍历构造二叉树。
注意: 你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder.length == 0 || postorder.length == 0) {
return null;
}
TreeNode root = new TreeNode(postorder[postorder.length - 1]);
for (int i = 0; i < inorder.length; i++) {
if (postorder[postorder.length - 1] == inorder[i]) {
int[] inLeft = Arrays.copyOfRange(inorder, 0, i);
int[] inRight = Arrays.copyOfRange(inorder, i + 1, inorder.length);
int[] postLeft = Arrays.copyOfRange(postorder, 0, i);
int[] postRight = Arrays.copyOfRange(postorder, i, inorder.length - 1);
root.left = buildTree(inLeft, postLeft);
root.right = buildTree(inRight, postRight);
break;
}
}
return root;
}
}