2018.7.30 《剑指Offer》从零单刷个人笔记整理(66题全)目录传送门
思路其实和之前做过的#数据结构与算法学习笔记#PTA11:先序遍历+中序遍历转后序遍历/二叉树非递归遍历/二叉树栈遍历(JAVA)是一样的。
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
JAVA实现:
/**
*
* @author ChopinXBP
* 题目描述
* 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
* 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
* 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
*
*/
public class ReconstructBinaryTree {
public static class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){val = x;}
}
private static int[]pre = {1,2,4,7,3,5,6,8};
private static int[]in = {4,7,2,1,5,3,8,6};
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode BinTree = ReConstructBinaryTree(pre, in);
System.out.println("Over");
}
//根据前序遍历与中序遍历重构二叉树
//注意:原题中pre与in并非全局变量,需要对函数参数进行相应修改
public static TreeNode ReConstructBinaryTree(int []pre, int[] in){
TreeNode BinTree = new TreeNode(pre[0]);
int flag = 0;
int head = 0;
int tail = in.length-1;
int root = Find(pre[0]);
if(root != -1){
ReConstructSolution(BinTree, flag, head, tail, root);
}
return BinTree;
}
//递归重构二叉树
private static void ReConstructSolution(TreeNode tree, int flag, int head, int tail, int root){
//左右子树均有,先递归重建左子树,后递归重建右子树
if(root != head && root!= tail){
int leftroot = pre[flag+1];
tree.left = new TreeNode(leftroot);
ReConstructSolution(tree.left, flag+1, head, root-1, Find(leftroot));
int rightroot = pre[flag+(root-head)+1];
tree.right = new TreeNode(rightroot);
ReConstructSolution(tree.right, flag+(root-head)+1, root+1, tail, Find(rightroot));
}
//只有右子树,递归重建右子树
else if(root == head && root != tail){
int rightroot = pre[flag+(root-head)+1];
tree.right = new TreeNode(rightroot);
ReConstructSolution(tree.right, flag+(root-head)+1, root+1, tail, Find(rightroot));
}
//只有左子树,递归重建左子树
else if(root == tail && root != head){
int leftroot = pre[flag+1];
tree.left = new TreeNode(leftroot);
ReConstructSolution(tree.left, flag+1, head, root-1, Find(leftroot));
}
}
//返回中序遍历数组某一元素所在位置
private static int Find(int data){
for(int i = 0;i
C++实现参考:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
struct TreeNode* reConstructBinaryTree(vector pre,vector in) {
int inlen=in.size();
if(inlen==0)
return NULL;
vector left_pre,right_pre,left_in,right_in;
//创建根节点,根节点肯定是前序遍历的第一个数
TreeNode* head=new TreeNode(pre[0]);
//找到中序遍历根节点所在位置,存放于变量gen中
int gen=0;
for(int i=0;ileft=reConstructBinaryTree(left_pre,left_in);
head->right=reConstructBinaryTree(right_pre,right_in);
return head;
}
};
#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#