从父数组测试用例构造二叉树失败

Construct Binary Tree from Parent Array test case failing

本文关键字:二叉树 失败 测试用例 数组      更新时间:2023-10-16

问题的链接-[链接][1]

基本上,我们得到了一个整数数组及其大小。问题是从中构造一个二叉树。每个索引对应于存储在节点中的数据,该索引的值是父级的数据。根节点索引的值将始终为 -1,因为根没有父级。输出将是树的排序级别顺序遍历。

现在我的方法是将数组从 1 解析为 n(不是第 0 个元素/根节点),对于每个元素,我使用第一个函数获取它的父级,并相应地插入子元素。但是一个特定的测试用例失败了。也许网站自己的输出不正确。我将在下面发布所有内容:-

示例测试用例-

阵列大小-7

元素- -1 0 0 1 1 3 5

输出- 0 1 2 3 4 5 6

特定的测试用例(这是我的疑问)-

数组大小 - 42

元素-

3 19 1 41 35 29 27 11 17 23 9 15 33 13 39 23 19 25 21 1 33 15 31 21 5 7 37 29 7 11 31 39 -1 27 3 9 25 17 13 41 37 35网站输出 - 32

我的输出 - 0

功能


void getParent(Node* root, int val, Node* &main)
{
if(root==NULL) return;
if(root->data==val){
main=root;
return;
}
getParent(root->left,val,main);
getParent(root->right,val,main);

}
Node *createTree(int parent[], int n)
{
if(n==0) return NULL;
Node * root=new Node(0);
for(int i=1;i<n;i++)
{
Node* main=NULL;
getParent(root,parent[i],main);
//main has the parent

Node* child=new Node(i);
if(main==NULL) break;


if(main->left==NULL)
{
main->left=child;
}
else if(main->right==NULL)
{
main->right=child;
}
}
return root;
} 

[1]: https://www.geeksforgeeks.org/construct-a-binary-tree-from-parent-array-representation/
[2]: https://i.stack.imgur.com/0fRmn.png

不确定你用getParent方法做什么。此外,您正在启动一个值为 0 的根节点,并且没有在循环中对其进行任何操作,然后最后返回根。我怀疑你的根总是有一个值 0。

解决方案实际上非常简单。使用每个节点的值作为数组的索引初始化节点数组。例如,对于大小为 5 的数组,您可以创建一个包含 5 个节点的数组,每个节点都有一个其所在索引的值。

然后下一步是遍历parent数组,看看位于parent[i]的节点是否具有leftright"可用",如果是,则相应地分配节点。

代码是:

Node* createTree(int parent[], int n) {
Node** nodes = new Node*[n];
for ( int i = 0; i < n; i++ )
nodes[i] = new Node(i);
int rootIndex = 0;
for ( int i  = 0; i < n; i++ ) {
if ( parent[i] == -1 ) {
rootIndex = i;
} else {
if ( nodes[parent[i]] -> left == NULL ) {
nodes[parent[i]] -> left = nodes[i];
} else if ( nodes[parent[i]] -> right == NULL ) {
nodes[parent[i]] -> right = nodes[i];
}
}

}
return nodes[rootIndex];
}