剑指offer的66题之第4题:重建二叉树
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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 12 public: 13 struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) { 14 int inlen=in.size(); 15 if(inlen==0) 16 return NULL; 17 vector<int> left_pre,right_pre,left_in,right_in; 18 //创建根节点,根节点肯定是前序遍历的第一个数 19 TreeNode* head=new TreeNode(pre[0]); 20 //找到中序遍历根节点所在位置,存放于变量gen中 21 int gen=0; 22 for(int i=0;i<inlen;i++) 23 { 24 if (in[i]==pre[0]) 25 { 26 gen=i; 27 break; 28 } 29 } 30 //对于中序遍历,根节点左边的节点位于二叉树的左边,根节点右边的节点位于二叉树的右边 31 //利用上述这点,对二叉树节点进行归并 32 for(int i=0;i<gen;i++) 33 { 34 left_in.push_back(in[i]); 35 left_pre.push_back(pre[i+1]);//前序第一个为根节点 36 } 37 for(int i=gen+1;i<inlen;i++) 38 { 39 right_in.push_back(in[i]); 40 right_pre.push_back(pre[i]); 41 } 42 //和shell排序的思想类似,取出前序和中序遍历根节点左边和右边的子树 43 //递归,再对其进行上述所有步骤,即再区分子树的左、右子子数,直到叶节点 44 head->left=reConstructBinaryTree(left_pre,left_in); 45 head->right=reConstructBinaryTree(right_pre,right_in); 46 return head; 47 } 48 };
下面方法传递的参数是数组:
1 public class Solution { 2 public TreeNode reConstructBinaryTree(int [] pre,int [] in) { 3 TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1); 4 return root; 5 } 6 //前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6} 7 private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) { 8 9 if(startPre>endPre||startIn>endIn) 10 return null; 11 TreeNode root=new TreeNode(pre[startPre]); 12 13 for(int i=startIn;i<=endIn;i++) 14 if(in[i]==pre[startPre]){ 15 root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1); 16 root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn); 17 break; 18 } 19 20 return root; 21 } 22 }
Python代码实现:
1 class Solution: 2 def reConstructBinaryTree(self, pre, tin): 3 if not pre or not tin: 4 return None 5 root = TreeNode(pre.pop(0)) 6 index = tin.index(root.val) 7 root.left = self.reConstructBinaryTree(pre, tin[:index]) 8 root.right = self.reConstructBinaryTree(pre, tin[index + 1:]) 9 return root
上面参考:https://www.nowcoder.com/profile/8429923/codeBookDetail?submissionId=17421023
关于:二叉树及其三种遍历:
https://blog.csdn.net/qq_40772692/article/details/79343914
https://www.cnblogs.com/xinchrome/p/4905608.html
https://blog.csdn.net/weixin_35909255/article/details/55071068

浙公网安备 33010602011771号