问题描述
|
这是二进制搜索树的代码
#include<stdio.h>
#include<conio.h>
#include\"malloc.h\"
struct node
{
int data;
struct node* left;
struct node* right;
};
int size(struct node* n)
{
if(n==NULL)
return 0;
else
return (size(n->left)+1+size(n->right));
}
int maxdepth(struct node* n)
{
int ldepth,rdepth;
if(n==NULL)
{
return 0;
}
else
{
ldepth=maxdepth(n->left);
rdepth=maxdepth(n->right);
if(ldepth>rdepth)
return (ldepth+1);
else
return (rdepth+1);
}
}
int lookup(struct node* node,int target)
{
if(node==NULL)
return 0;
else if(target==node->data)
return 1;
else if(target<node->data)
return(lookup(node->left,target));
else
return(lookup(node->right,target));
}
struct node* newnode(int data)
{
struct node* newnod=(struct node*)malloc(sizeof(struct node));
newnod->data=data;
newnod->left=NULL;
newnod->right=NULL;
return newnod;
}
struct node* insert(struct node* root,int target)
{
if(root==NULL)
return(newnode(target));
else if(target<=root->data)
root->left=insert(root->left,target);
else
root->right=insert(root->right,target);
return root;
}
void main()
{
int result,s,max;
struct node* newnode=NULL;
clrscr();
newnode=insert(newnode,2);
newnode=insert(newnode,3);
newnode=insert(newnode,4);
max=maxdepth(newnode);
printf(\"maxdepth %d\\n\",max);
s=size(newnode);
result=lookup(newnode,3);
printf(\"size %d\\n\",s);
printf(\"%d\",result);
getch();
}
当我运行该程序时。我得到maxdepth
有3。
如果我将maxdepth
函数更改为
int maxdepth(struct node* n)
{
int ldepth,rdepth;
if(n==NULL)
{
return 0;
}
else
{
ldepth=maxdepth(n->left);
rdepth=maxdepth(n->right);
if(ldepth>rdepth)
return (ldepth);
else
return (rdepth);
}
}
我将maxdepth
值设为0。这是什么问题?我不明白吗?
解决方法
您没有计算当前节点,因此需要
+1
。
{
ldepth = maxdepth(n->left);
rdepth = maxdepth(n->right);
if(ldepth > rdepth)
return ldepth + 1;
else
return rdepth + 1;
}
没有the5ѭmaxdepth
总是返回0
。因为ldepth
和rdepth
将始终是0
。
具有3个节点的树的示例:
A
/ \\
B C
现在调用maxdepth(A)
,它将执行:ldepth = maxdepth(B); rdepth = maxdepth(C);
,然后maxDepth(B)
将进行:ldepth = maxdepth(null); rdepth = maxdepth(null); /* ldepth and rdepth are now 0 */
,因此maxDepth(B)
将返回结果0
。类似的ѭ20return将返回0
。然后,您将执行以下操作:
if(ldepth > rdepth)
return ldepth;
else
return rdepth;
但是ldepth
和rdepth
都是0
,因此将返回rdepth
,即0
。最后,maxdepth(A)
将返回0。
这就是为什么需要5英镑的原因。
, 让我们看一个示例树:
__A__
/ \\
B C
/ \\ / \\
D E F G
在这棵树中,我们处于完美平衡状态,因此我们不必担心每个节点上哪个子树更高(它们的高度相同)。因此,我们将只使用左侧分支来计算高度。
那棵树的高度是多少?这是ѭ31的高度。
A
的高度是多少?它是高度B
的一加。
反过来,ѭ33的高度为1加上ѭ35的高度,and35的高度为1加上ѭ35的左分支的高度(为零)。
因此总高度为1 + 1 + 1 + 0 = 3
。
因此,这种(简化)情况下的算法为:
def height (node):
if node is null:
return 0
return 1 + height (node.left)
这就是为什么递归高度函数必须在每个级别添加一个。如果改为加0(这是第二个代码段的作用),则从获得1 + 1 + 1 + 0 = 3
切换为获得0 + 0 + 0 + 0 = 0
。
如果您修改上述算法以考虑子树的不同大小,则基本上可以得到第一个代码段,该代码段运行良好:
def height (node):
if node is null:
return 0
leftheight = height (node.left)
rightheight = height (node.rigth)
return 1 + max (leftheight,rightheight)