题目
描述
求给定二叉树的最大深度,
深度是指树的根节点到任一叶子节点路径上节点的数量。
最大深度是所有叶子节点的深度的最大值。
(注:叶子节点是指没有子节点的节点。)
数据范围:
0≤n≤100000,树上每个节点的val满足 ∣val∣≤100
要求: 空间复杂度 O(1),时间复杂度 O(n)
思路
实际上就是层序遍历,记录下层数就可以。
代码
python版本:
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param root TreeNode类
# @return int整型
#
class Solution:
def maxDepth(self , root: TreeNode) -> int:
# write code here
if(root==None):
return 0
res=0
queue = [root]
while(len(queue)):
nnpl = len(queue)
for i in range(nnpl):
root = queue.pop()
if(root.left):
queue.insert(0, root.left)
if(root.right):
queue.insert(0, root.right)
res += 1
return res
c++版本:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型
*/
int maxDepth(TreeNode* root) {
// write code here
if(root==nullptr){
return 0;
}
queue<TreeNode*> q;
q.push(root);
int res=0;
while(!q.empty()){
int nnpl = q.size();
for(int i=0; i<nnpl; i++){
root = q.front();
q.pop();
if(root->left){
q.push(root->left);
}
if(root->right){
q.push(root->right);
}
}
res ++;
}
return res;
}
};