这是二叉搜索树的代码
#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.问题是什么?我想不出来?
答案 0 :(得分:6)
您没有计算当前节点,因此需要+1
。
{
ldepth = maxdepth(n->left);
rdepth = maxdepth(n->right);
if(ldepth > rdepth)
return ldepth + 1;
else
return rdepth + 1;
}
如果没有+1
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
maxDepth(C)
1}}。类似的0
将返回if(ldepth > rdepth)
return ldepth;
else
return rdepth;
。那你就做了:
ldepth
但rdepth
和0
都是rdepth
,因此0
将返回maxdepth(A)
。最后+1
将返回0作为结果。
这就是为什么需要{{1}}。
答案 1 :(得分:5)
让我们看一个示例树:
__A__
/ \
B C
/ \ / \
D E F G
在这棵树中,我们完全平衡,所以我们不会担心哪个是每个节点处的较高子树(它们的高度相同)。所以我们只用左侧分支来计算高度。
树的高度是多少?这是A
的高度。
A
的高度是多少?这是一个加上B
的高度。
反过来,B
的高度加一D
的高度,D
的高度加一D
左分支的高度,这是零。
总高度为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)