题干:
力扣这里给了定义:二叉树的最大深度指的是从根节点开始,到最远叶子所经过的节点数。
代码:
class Solution {//递归实现
public:int maxDepth(TreeNode* root) {if(root == NULL)return NULL;int leftheight = maxDepth(root -> left);int rightheight = maxDepth(root -> right);int height = 1 + max(leftheight, rightheight);return height;}
};
class Solution {//迭代实现
public:int maxDepth(TreeNode* root) {int count = 0;queue<TreeNode*> que;vector<vector<int>> res;if(root != NULL) que.push(root);while(!que.empty()){int size = que.size();vector<int> tmp;while(size--){TreeNode* node = que.front();que.pop();tmp.push_back(node -> val);if(node -> left) que.push(node -> left);if(node -> right) que.push(node -> right);if(size == 0) count+=1;}}return count;}
};