LC.104.二叉树的最大深度(DFS&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 ans;
void dfs(TreeNode* root,int d){
if(root==nullptr){
ans=max(ans,d);
return ;
}
dfs(root->left,d+1);
dfs(root->right,d+1);
}
int maxDepth(TreeNode* root) {
ans=0;
dfs(root,0);
return ans;
}
};
/**
* 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==nullptr) return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
的代码就不写了,根先入队,主要是分层,每过一层深度加1,比较好写。