题目来自于:
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
这一题目其实我想说的还不是我的代码,是之前在写代码中遇到的一个bug问题。后面会进行详细的解释
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildhelp(vector& preorder, vector& inorder,int pStart,int pEnd,int iStart,int iEnd){
if(pStart>pEnd||iStart>iEnd)
return NULL;
TreeNode *Tnode=new TreeNode(preorder[pStart]);
if(pStart==pEnd)
return Tnode;
int cur=iStart;
while(inorder[cur]!=preorder[pStart])
cur++;
Tnode->left=buildhelp(preorder, inorder,pStart+1,pStart+(cur-iStart),iStart,cur-1);
Tnode->right=buildhelp(preorder, inorder,pEnd-(iEnd-cur-1),pEnd,cur+1,iEnd);
return Tnode;
}
TreeNode* buildTree(vector& preorder, vector& inorder) {
TreeNode* Tree=NULL;
if(preorder.size()==0)
return Tree;
Tree=buildhelp(preorder, inorder,0,preorder.size()-1,0,inorder.size()-1);
return Tree;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildhelp(vector& preorder, vector& inorder,int pStart,int pEnd,int iStart,int iEnd){
if(pStart& preorder, vector& inorder) {
TreeNode* Tree=NULL;
if(preorder.size()==0)
return Tree;
Tree=buildhelp(preorder, inorder,0,preorder.size()-1,0,inorder.size()-1);
return Tree;
}
};
TreeNode Tnode(preorder[pStart]);
然后返回其指针
这里犯了一个很大的错误就是,其实每次算法在遇到该处时候只是将结构体中的成员变量替换成了新的,却没有构建新的节点。
为了验证我们的想法:
#include
#include
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main()
{
int i=5;
while(i--)
{
TreeNode aa(i);
cout<<&aa<
我们在一个while中多次重建该结构体但是其地址都没有发生改变
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
class Solution {
public:
TreeNode* buildhelp(vector& inorder, vector& postorder,int iStart,int iEnd,int pStart,int pEnd){
if(pStart>pEnd||iStart>iEnd)
return NULL;
TreeNode *Tnode=new TreeNode(postorder[pEnd]);
if(pStart==pEnd)
return Tnode;
int cur=iStart;
while(inorder[cur]!=postorder[pEnd])
cur++;
Tnode->left=buildhelp(inorder, postorder,iStart,cur-1,pStart,pStart+(cur-iStart-1));
Tnode->right=buildhelp(inorder, postorder,cur+1,iEnd,pEnd-1-(iEnd-cur-1),pEnd-1);
return Tnode;
}
TreeNode* buildTree(vector& inorder, vector& postorder) {
if(inorder.size()==0)
return NULL;
return buildhelp(inorder, postorder,0,inorder.size()-1,0,postorder.size()-1);
}
};