重建二叉树
Posted mokayy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了重建二叉树相关的知识,希望对你有一定的参考价值。
/*输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。/** * 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* ConstructBinaryTree(vector<int> pre,int preStart,int preEnd,vector<int> in,int inStart,int inEnd) { TreeNode* root = new TreeNode(pre[preStart]); if((preEnd == preStart)&&(inEnd == inStart)&&(in[inStart]==pre[preStart])) return root; int i = inStart; while((i<=inEnd)&&(in[i]!=pre[preStart])){ i++; } int lenf = i -inStart; int lenr = inEnd - i ; int leftpreEnd = preStart+lenf ; if(lenf>0){ root->left = ConstructBinaryTree(pre,preStart+1,leftpreEnd,in,inStart,i-1); } if(lenr>0){ root->right = ConstructBinaryTree(pre,leftpreEnd+1,preEnd,in,i+1,inEnd); } return root; } struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) { int len = pre.size(); if(len == 0) return NULL; return ConstructBinaryTree(pre,0,len-1,in,0,len-1); } };
以上是关于重建二叉树的主要内容,如果未能解决你的问题,请参考以下文章