1. 递归
二叉树的最大深度 = max(左子树深度 + 右子树深度) + 1
只考虑根节点是否为空,其余交给递归处理
深度优先
#include<algorithm>
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
return max(maxDepth(root->left),maxDepth(root->right)) + 1;
}
};
2. 广度优先遍历
树的遍历分为广度优先遍历(BFS)和深度优先遍历(DFS)。
广度优先遍历使用队列,树的节点逐层添加到队列。
本题需要计算深度,则需要知道每层节点的数目,或队列中只保存一层节点,节点的数目可以用queue.size()
计算出
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
queue<TreeNode*> Q;
Q.push(root);
int depth = 0;
while(!Q.empty()) {
int levelSize = Q.size();
for(int i=0; i<levelSize; ++i) {
TreeNode* node = Q.front();
Q.pop();
if(node->left != NULL) Q.push(node->left);//对空指针的判断容易漏
if(node->right!= NULL) Q.push(node->right);
}
++depth;
}
return depth;
}
};