【剑指offer】【树】55-I.二叉树最大深度
题目链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/
DFS(递归法)
/**
* 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;
}
};
BFS(借助队列)
/**
* 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;
queue<TreeNode *> q;
q.push(root);
int res = 0;
while(!q.empty())
{
int n = q.size();
while(n--)
{
TreeNode* tmp = q.front();
q.pop();
if(tmp -> left) q.push(tmp -> left);
if(tmp -> right) q.push(tmp -> right);
}
res++;
}
return res;
}
};
知识的价值不在于占有,而在于使用