如何解决我试图找到具有给定顺序和预给定的二叉树,但我遵循的是递归方法,但是输出错误
我正在采用递归方法来解决该问题。代码中没有语法错误
/**************** **We are given Inorder and Preorder . We have to find the Binary Tree.** ***************/
#include <iostream>
using namespace std;
#include <queue>
template<typename T>
/* Class Defination */
class BinaryTreeNode
{
public:
T data;
BinaryTreeNode *left;
BinaryTreeNode *right;
BinaryTreeNode(T data)
{
this->data = data;
left = NULL;
right = NULL;
}
~BinaryTreeNode()
{
delete left;
delete right;
}
};
/* *Function to print to the Tree* */
void printTreeLevelWise(BinaryTreeNode<int> *root)
{
if (root == NULL)
{ //Base case
return;
}
queue<BinaryTreeNode<int>*> pendingNodes;
pendingNodes.push(root);
while (pendingNodes.size() != 0)
{
BinaryTreeNode<int> *front = pendingNodes.front();
pendingNodes.pop();
cout << front->data << ":";
if (front->left != NULL)
{
cout << "L" << front->left->data;
pendingNodes.push(front->left);
}
if (front->right != NULL)
{
cout << "R" << front->right->data;
pendingNodes.push(front->right);
}
cout << endl;
}
}
/* **Building the Tree** */
BinaryTreeNode<int>* buildTreeHelper(int *in,int *pre,int inS,int inE,int preS,int preE)
{
if (inS > inE)
{
return NULL;
}
int rootData = pre[preS];
int rootIndex = -1;
for (int i = inS; i <= inE; i++)
{
if (in[i] == rootData)
{
rootIndex = i;
break;
}
}
int lInS = inS;
int lInE = rootIndex - 1;
int lPreS = preS + 1;
int lPreE = lInE - lInS + lPreS;
int rPreS = lPreE + 1;
int rPreE = preE;
int rInS = rootIndex + 1;
int rInE = inE;
BinaryTreeNode<int> *root = new BinaryTreeNode<int>(rootData);
root->left = buildTreeHelper(in,pre,lInS,lInE,lPreS,lPreE);
root->left = buildTreeHelper(in,rInS,rInE,rPreS,rPreE);
return root;
}
BinaryTreeNode<int>* buildTree(int *in,int size)
{
return buildTreeHelper(in,size - 1,size - 1);
}
int main()
{
int in[] = { 4,2,5,1,8,6,9,3,7 };
int pre[] = { 1,4,7 };
BinaryTreeNode<int> *root = buildTree(in,9);
printTreeLevelWise(root);
delete root;
return 0;
}
解决方法
至少第二行应为root->right = ...
:
root->left = buildTreeHelper(in,pre,lInS,lInE,lPreS,lPreE);
root->left = buildTreeHelper(in,rInS,rInE,rPreS,rPreE);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。