題目鏈接
tag:
- easy;
- DFS铺敌;
question:
??Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
解法一:
??求二叉樹的最大深度問題用到深度優(yōu)先搜索DFS
桅滋,遞歸的完美應(yīng)用著洼。代碼如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
解法二:
??也可以使用層序遍歷艘希,然后計數(shù)總層數(shù)妇蛀,即為二叉樹的最大深度,代碼如下:
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
int res = 0;
queue<TreeNode*> q{{root}};
while (!q.empty()) {
++res;
for (int i = q.size(); i > 0; --i) {
TreeNode *t = q.front(); q.pop();
if (t->left)
q.push(t->left);
if (t->right)
q.push(t->right);
}
}
return res;
}
};