Maximum Depth of Binary Tree
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.
/**
* 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 n=0;
int maxDepth(TreeNode* root) { // 递归
if(root==NULL) return 0; //为空则返回 0
return 1+max(maxDepth(root->left),maxDepth(root->right)); //不为空 则返回 左右子树的最大深度 加上1
}
int maxDepth(TreeNode* root) { // 非递归
if(!root) return 0;
int num=0; // 记录 最大深度
int count_=0; // 每一层的节点数
queue<TreeNode*>q;
q.push(root);
count_=1;
while(!q.empty()){
TreeNode* x=q.front();
q.pop();
count_--;
if(x->left) q.push(x->left);
if(x->right) q.push(x->right);
if(count_==0){ // count_==0 此层的节点访问完 num++
count_=q.size();
num++;
}
}
return num;
}
};