先看Leetcode104:Maximum Depth of Binary Tree,求二叉树最大深度。
有两种解法,基于DFS(深度优先搜索)思想的方法使用递归计算:
class Solution {
public:
int maxDepth(TreeNode *root) {
if(root == nullptr)
return 0;
int lef = maxDepth(root->left);
int rig = maxDepth(root->right);
return (lef > rig ? lef : rig) + 1;
}
};
运行时间:10ms,占用内存:864k
基于BFS(宽度/广度优先搜索)思想的方法使用非递归计算,采用层序遍历,需要引入队列:
class Solution {
public:
int maxDepth(TreeNode *root) {
if(root == nullptr)
return 0;
queue <TreeNode *> que; // 将二叉树中的元素逐层添加到队列中,层序遍历到最后一层
int nCount = 1; // 每一层中节点个数,根节点这一层只有1个节点故初始化为1
int nDepth = 0; // 记录深度
que.push(root);
while(!que.empty()){
TreeNode * pTemp = que.front(); // 取出队首元素
que.pop(); // 弹出队首元素
--nCount; // 逐个元素弹出
if(pTemp->left) // 将下一层的节点添加到队列中
que.push(pTemp->left);
if(pTemp->right)
que.push(pTemp->right);
if(nCount == 0){ // 这一层节点已经遍历完
nCount = que.size(); // nCount是下一层节点数目
++nDepth; // 深度+1
}
}
return nDepth;
}
};
运行时间:8ms,占用内存:884k
求最小二叉树深度跟求最大二叉树深度类似,不同点在于求最小深度时需要判断左右节点,因为当一个节点只有左子树或右子树时,不能直接取其左右子树中最小的深度,因为那个深度是0(因为只有一个子树),树的深度必须要到叶子节点才行(既没有左子树也没有右子树)。而求最大深度的时候,因为每一个子树取的都是最大深度,就不会有非叶子节点判断错误的问题了。
1.基于DFS:
class Solution {
public:
int run(TreeNode *root) {
if(root == nullptr)
return 0;
if(root->left == nullptr)
return run(root->right) + 1;
if(root->right == nullptr)
return run(root->left) + 1;
return min(run(root->left),run(root->right)) + 1;
}
};
运行时间:12ms,占用内存:848k
2.基于BFS:
class Solution {
public:
int run(TreeNode *root) {
if(root == NULL)
return false;
queue<TreeNode *> que;
TreeNode *last, *cur;
int level = 1, size = 0;
last = cur = root;
que.push(root);
while(!que.empty()){
cur = que.front();
que.pop();
size = que.size();
if(cur->left)
que.push(cur->left);
if(cur->right)
que.push(cur->right);
if(que.size() == size) //循环终止条件
break;
if(last == cur){
level++;
if(que.size() != 0)
last = que.back();
}
}
return level;
}
}