计算二叉树的深度(高度):深度优先遍历(DFS递归实现)、广度优先遍历(BFS,层次遍历)
先简要概述两种遍历的优缺点:
深度优先搜素算法:不全部保留结点,占用空间少;有回溯操作,运行速度慢。
广度优先搜索算法:保留全部结点,占用空间大; 无回溯操作,运行速度快。
-
通常深度优先搜索法不全部保留结点,扩展完的结点从数据库中弹出删去,这样,一般在数据库中存储的结点数就是深度值,因此它占用空间较少。所以,当搜索树的结点较多,用其它方法易产生内存溢出时,深度优先搜索不失为一种有效的求解方法。
-
广度优先搜索算法,一般需存储产生的所有结点,占用的存储空间要比深度优先搜索大得多,因此,程序设计中,必须考虑溢出和节省内存空间的问题。但广度优先搜索法一般无回溯操作,所以运行速度比深度优先搜索要快些。
数据结构:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
};
代码示例:
DFS:
int maxDepth(TreeNode *root){
if(root == NULL) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) +1;
}
BFS(层次遍历):
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
queue<TreeNode*> nodeQueue;
nodeQueue.push(root);
TreeNode *node; //null pointer
int depth=0; //max depth
while(!nodeQueue.empty()){
int que_len = nodeQueue.size();
for(int i=0; i<que_len;i++){
node = nodeQueue.front();
nodeQueue.pop();
if(node->left) nodeQueue.push(node->left);
if(node->right) nodeQueue.push(node->right);
}
depth++;
}
return depth;
}
LeetCode练习:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/