面试题07 重建二叉树(java)

输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

 

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7
 

限制:

0 <= 节点个数 <= 5000

 

注意:本题与主站 105 题重复:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
 * 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(0, preorder.length, 0, inorder.length, preorder, inorder);
    }
    public TreeNode build(int preBegin, int preorderSize, int inBegin, int inorderSize, int[] preorder, int[] inorder) {
        if(preorderSize == 0) return null;
        TreeNode T = new TreeNode(preorder[preBegin]);
        int i = 0;
        for(; inorder[inBegin+i] != T.val; i++);
        preBegin++;
        T.left = build(preBegin, i, inBegin, i, preorder, inorder);
        preBegin += i;
        inBegin += i + 1;
        i = preorderSize - i - 1;
        T.right = build(preBegin, i, inBegin, i, preorder, inorder);
        return T;
    }
}

你可能感兴趣的:(leetcode剑指offer)