题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
递归解法:
/**
* 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,inorder,0,preorder.length-1,0,inorder.length-1);
}
private TreeNode build(int[] preorder, int[] inorder,int preStart,int preEnd,int inStart,int inEnd){
if (preStart > preEnd || inStart > inEnd || preStart >= preorder.length || inStart >= inorder.length)
return null;
int rootVal = preorder[preStart];
int offset = 0;
while(inorder[offset+inStart] != rootVal){
offset++;
}
TreeNode root = new TreeNode(rootVal);
root.left = build(preorder,inorder,preStart+1,preStart+offset,inStart,inStart+offset);
root.right = build(preorder,inorder,preStart+offset+1,preEnd,inStart+offset+1,inEnd);
return root;
}
}
网友评论