首页 > 代码库 > 重建二叉树

重建二叉树

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {13         /*14         解题思路:15             1、构建递归调用函数,将先序遍历数组pre和中序遍历数组in,    及其对应的起始位置和长度作为实参16         */17         TreeNode *root=constructBinaryTree(pre,0,pre.size()-1,in,0,in.size()-1);18         return root;19     }20         TreeNode *constructBinaryTree(vector<int> pre,int pre_start,int pre_end,vector<int> in,int in_start,int in_end){21         //递归退出的条件22             if(pre_start>pre_end||in_start>in_end){23                return NULL;24             }25               TreeNode *root=(TreeNode *)malloc(sizeof(TreeNode));//创建根节点26               root->val=pre[pre_start];27            for(int i=in_start;i<=in_end;i++){28                if(pre[pre_start]==in[i]){29                  root->left=constructBinaryTree(pre,pre_start+1,pre_start+(i-in_start),in,in_start,i-1);//将左子树传入(数组,及其对应的下标)30                  root->right=constructBinaryTree(pre,pre_start+i-in_start+1,pre_end,in,i+1,in_end); //将右子树传入31               }     32           }33           return root;34     }35 };

 

重建二叉树