(一)递归求深度
int TreeDeepth_Recur(TreeNode *root){
if(root == NULL) return 0;
int left_deepth, right_deepth ;
left_deepth = TreeDeepth_Recur(root->left);
right_deepth = TreeDeepth_Recur(root->right);
return (left_deepth > right_deepth)?left_deepth + 1:right_deepth + 1;
}
(二)非递归求深度
采用BFS的思想,记录每层的深度,遍历到最后一层后,所记录的深度就是整棵树的深度。
int TreeDeepth(TreeNode *root){
if(root == NULL) return 0;
typedef std::pair<TreeNode*, int> PTI;
queue<PTI> q;
q.push(PTI(root, 1));
PTI curnode ;
int curdeepth = 1; //用于记录深度
while(!q.empty()){
curnode = q.front();
q.pop();
curdeepth = curnode.second;
if(curnode.first->left)
q.push(PTI(curnode.first->left, curnode.second + 1));
if(curnode.first->right)
q.push(PTI(curnode.first->right, curnode.second + 1));
}
return curdeepth;
}
调用接口:
int main(void)
{
TreeNode *root = NULL;
PreoderBuildTree(root);
std::cout << TreeDeepth_Recur(root);
std::cout << std::endl;
std::cout << TreeDeepth(root);
std::cout << std::endl;
}