想要用后序遍历实现找出二叉树的高度,写了以下算法:
int SyntaxTree::Height(TreeNode* t)
{
if(t==NULL) return 0; //空树
int hl=Height(t->Left);
int hr=Height(t->Right);
if(hl>hr)
return ++hl;
else
return ++hr;
}对应结点结构为:
struct TreeNode{
int code;
union{
float value;
int table_;
TreeNode* notleaf; //非叶子结点
}Leaf;
TreeNode* Left;//左孩子
TreeNode* Right;//右孩子
};在main函数中建树输出二叉树的信息无误,可是如果调用求高度函数时,没有报错,但是会跳出:遇到严重错误,test.exe要关闭,单步跟踪发现在运行到Height(t->Left);就停了,跳出如下错误信息:
Unhandled exception in test.exe:0xc0000005:Access Violation
请问,以上求高度算法有错吗?如何改正?
int SyntaxTree::Height(TreeNode* t)
{
if(t==NULL) return 0; //空树
int hl=Height(t->Left);
int hr=Height(t->Right);
if(hl>hr)
return ++hl;
else
return ++hr;
}对应结点结构为:
struct TreeNode{
int code;
union{
float value;
int table_;
TreeNode* notleaf; //非叶子结点
}Leaf;
TreeNode* Left;//左孩子
TreeNode* Right;//右孩子
};在main函数中建树输出二叉树的信息无误,可是如果调用求高度函数时,没有报错,但是会跳出:遇到严重错误,test.exe要关闭,单步跟踪发现在运行到Height(t->Left);就停了,跳出如下错误信息:
Unhandled exception in test.exe:0xc0000005:Access Violation
请问,以上求高度算法有错吗?如何改正?
那出现这种报错的Unhandled exception in test.exe:0xc0000005:Access Violation
就是说可能是树的建立有问题了?可是输出的树结点又正确哪,而且输出的时候没有改动树啊。
Unhandled exception in test.exe:0xc0000005:Access Violation
应该是指针访问了不该访问的地方。