重建二叉树递归调用返回值的问题。
一:#include <iostream>
#include <vector>
using namespace std;
struct node
{
int val;
struct node *left;
struct node *right;
node(int x):val(x),left(NULL),right(NULL){}
};
class TreeNode
{
public:
node *re_construct_tree(const vector<int> &pre,const vector<int> &in);
void pre_order(node *root);
node *root;
};
node *TreeNode::re_construct_tree(const vector<int> &pre,const vector<int> &in)
{
int pre_len=pre.size();
int in_len=in.size();
if(pre_len==0||in_len==0||pre_len!=in_len)
return NULL;
root=new node(pre[0]);//先序遍历中第一个结点为根节点,为什么递归之后是最后返回的是最后一个节点8,而不是第一次的赋值1
int root_index=0;
for(int i=0;i<in_len;++i)//找根结点在中序中的下标
if(in[i]==pre[0])
{
root_index=i;
break;
}
vector<int> pre_left,pre_right,in_left,in_right;
for(int i=0;i<root_index;++i)//左子树
{
pre_left.push_back(pre[i+1]);
in_left.push_back(in[i]);
}
for(int i=root_index+1;i<pre_len;++i)//右子树
{
pre_right.push_back(pre[i]);
in_right.push_back(in[i]);
}
root->left=re_construct_tree(pre_left,in_left);
root->right=re_construct_tree(pre_right,in_right);
}
void TreeNode::pre_order(node *root)
{
if(root!=NULL)
{
cout<<root->val<<endl;//只输出先序中最后一个节点的值8,
pre_order(root->left);
pre_order(root->right);
}
}
int main()
{
int pre[]={1,2,4,7,3,5,6,8};
int in[]={4,7,2,1,5,3,8,6};
vector<int> p(pre,pre+sizeof(pre)/sizeof(pre[0]));
vector<int> i(in,in+sizeof(in)/sizeof(in[0]));
TreeNode t;
t.re_construct_tree(p,i);//把根节点定义成类的成员变量,递归调用的返回值是先序中最后的一个结点的值,而不是递归之前的值,除了以下代码二中的解决办法请问还有没有其他的解决办法
t.pre_order(t.root);
return 0;
}
二:
#include <iostream>
#include <vector>
using namespace std;
struct node
{
int val;
struct node *left;
struct node *right;
node(int x):val(x),left(NULL),right(NULL){}
};
class TreeNode
{
public:
node *re_construct_tree(const vector<int> &pre,const vector<int> &in);
void pre_order(node *root);
};
node *TreeNode::re_construct_tree(const vector<int> &pre,const vector<int> &in)
{
int pre_len=pre.size();
int in_len=in.size();
if(pre_len==0||in_len==0||pre_len!=in_len)
return NULL;
node *root=new node(pre[0]);//先序遍历中第一个结点为根节点
int root_index=0;
for(int i=0;i<in_len;++i)//找根结点在中序中的下标
if(in[i]==pre[0])
{
root_index=i;
break;
}
vector<int> pre_left,pre_right,in_left,in_right;
for(int i=0;i<root_index;++i)//左子树
{
pre_left.push_back(pre[i+1]);
in_left.push_back(in[i]);
}
for(int i=root_index+1;i<pre_len;++i)//右子树
{
pre_right.push_back(pre[i]);
in_right.push_back(in[i]);
}
root->left=re_construct_tree(pre_left,in_left);
root->right=re_construct_tree(pre_right,in_right);
return root;
}
void TreeNode::pre_order(node *root)
{
if(root!=NULL)
{
cout<<root->val<<endl;
pre_order(root->left);
pre_order(root->right);
}
}
int main()
{
int pre[]={1,2,4,7,3,5,6,8};
int in[]={4,7,2,1,5,3,8,6};
vector<int> p(pre,pre+sizeof(pre)/sizeof(pre[0]));
vector<int> i(in,in+sizeof(in)/sizeof(in[0]));
TreeNode t;
node *root;
root=t.re_construct_tree(p,i);
t.pre_order(root);
return 0;
}