剑指Offer-重建二叉树

来源:互联网 发布:php api 框架 编辑:程序博客网 时间:2024/05/04 11:16

重建二叉树

题目描述:
  输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
  假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

解题思路:
(1)如果前序遍历为空或中序遍历为空或节点个数小于等于0,返回NULL。
(2)创建根节点。前序遍历的第一个数据就是根节点的数据,在中序遍历中找到根节点的位置,可分别得知左子树和右子树的前序和中序遍历序列,重建左右子树。

我的Java实现源代码:

/** * 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(null == pre || pre.length==0){            return null;        }        int treeLength = pre.length;        TreeNode node = new TreeNode(pre[0]);        int rootIndex = -1;        for(int i = 0 ; i<in.length; i++){            if(node.val == in[i]){                rootIndex=i;                break;            }        }        if(rootIndex == -1){            return null;        }        //重建左子树        int []leftPre = new int[rootIndex];        for(int i = 1,j=0 ; i <= rootIndex; i++){            leftPre[j++] = pre[i];        }        int []leftIn = new int[rootIndex];        for(int i = 0,j=0 ; i < rootIndex; i++){            leftIn[j++] = in[i];        }        node.left = reConstructBinaryTree(leftPre,leftIn);        //重建右子树        int []rightPre = new int[treeLength - rootIndex-1];        for(int i = rootIndex+1 ,j=0; i < treeLength; i++,j++){            rightPre[j] = pre[i];        }        int []rightIn = new int[treeLength - rootIndex-1];        for(int i = rootIndex+1,j=0 ; i < treeLength; i++,j++){            rightIn[j] = in[i];        }        node.right = reConstructBinaryTree(rightPre,rightIn);        return node;    }}
0 0
原创粉丝点击