重建二叉树(牛客网)

从前序遍历和中序遍历重建一个二叉树。

步骤如下:

1、根据前序遍历的第一个元素建立根节点

2、在中序遍历找到这个元素,左边的元素都是根节点的左子树的结点,右边的元素都是右子树的结点

3、在前序遍历中找到属于左右子树的前序序列

4、左子树重复123

5、右子树重复123

6、返回根节点

例如前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}

1、根节点 1

2、中序遍历中找到 1 ,左边4,7,2都是左子树的结点,右边5,3,8,6都是右子树的结点

3、左子树的前序序列2,4,7,右子树的前序序列3,5,6,8

4,左子树的根节点 2,左子树的结点4,7,右子树的结点 null

5,右子树的根节点 3,左子树的结点5,右子树的结点8,6

最后得到:

1

2 3

4 null 5 6

null 7 null null 8 null


上代码。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(in.length == 0){
            return null;
        }
        
        TreeNode node = new TreeNode(pre[0]);
        int index = 0;
        for(; index < in.length; index++){
            if(pre[0] == in[index]){
                break;
            }
        }
        
        int[] newPre = new int[index];
        int[] newIn = new int[index];
        for(int i = 0; i < index; i++){
            newPre[i] = pre[i + 1];
        }
        for(int i = 0; i < index; i++){
            newIn[i] = in[i];
        }
        node.left = reConstructBinaryTree(newPre, newIn);
        
        newPre = new int[pre.length - index - 1];
        newIn = new int[in.length - index - 1];
        for(int i = 0; i < pre.length - index - 1; i++){
            newPre[i] = pre[index + i + 1];
        }
        for(int i = 0; i < in.length - index - 1; i++){
            newIn[i] = in[index + i + 1];
        }
        node.right = reConstructBinaryTree(newPre, newIn);
        
        return node;
    }
}
经验分享 程序员 微信小程序 职场和发展