版权声明:如若转载,请联系作者。 https://blog.csdn.net/liu16659/article/details/89736967
二叉树相关编程常见错误 【C++版】
1.对指针理解不够
如下代码是我在为每个节点设置树高。但是其中有一处很明显的错误。
void btHigh(node* root)
{
if (root == NULL){
root->height = 0;
return ;//一定不要少了这个边界条件
}
btHigh(root->lchild);
btHigh(root->rchild);
//二叉树的高度为左子树和右子树中高的那个高度加1
int ret1 = root->lchild->height;
int ret2 = root->rchild->height;
root->height = ret1 > ret2 ? ret1 + 1 : ret2 + 1;
}
迄今为止,我发现的错误地方有:
1.1
if (root == NULL){
root->height = 0;
return ;//一定不要少了这个边界条件
}
这一步是典型的低级错误,怎么能在root=NULL
的时候给root->height
赋值呢? 也就是说,if中的判断是要有意义的,不是白判断的。