我有一个二叉树数据结构:
//Declare Data Structure
struct CP {
int id; //ID of the Node
int data; //Data of the Node
CP * left; //Pointer to the Left Subtree
CP * right; //Pointer to the Right Subtree
};
typedef CP * CPPtr;
在不更改树结构的情况下,如果给定节点 ID,我如何实际计算深度。 (id是每个树节点的唯一标识)
最佳答案
您的代码缺少一些基本步骤或必要的初始化。
BTree_Helper(BTree *Tree){// this is roughly written like pseudo code
if(TLeft == NULL && TRight == NULL){
depth of tree = 0 ;
}
else if (TLeft == NULL){
depth of tree = depth of right tree ;
}
else if(TRight==NULL){
depth of tree = depth of left tree;
}
else{
depth of tree = the maximum between depth of left and depth of right;
}
}
为了您的方便,我只是给出了一些提示。 仔细考虑并尝试尽可能多的测试套件。
关于c++ - C++ 中的二叉树基础知识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9677311/