LeetCode - 解题笔记 - 104 - Maximum Depth of Binary Tree

Solution 1

实际上就是之前 0102. Binary Tree Level Order Traversal 里面“一层一层算”的思路。所以,使用BFS就可以了,完成一层就+1。

  • 时间复杂度: O ( N ) O(N) O(N),其中 N N N为输入序列的节点个数,线性遍历处理输入
  • 空间复杂度: O ( 2 ⌊ log ⁡ N ⌋ ) O(2^{\lfloor \log N \rfloor}) O(2logN),其中 N N N为输入序列的节点个数,因为最坏情况下,最后一层全满,整个队列最大占用就是最后一层
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        int ans = 0;
        
        if (root != nullptr) {
            queue<TreeNode*> q;
            q.push(root);
            
            while (!q.empty()) {
                int numNodeLevel = q.size();
                
                while (numNodeLevel--) {
                    auto now = q.front();
                    q.pop();

                    auto left = now->left;
                    if (left != nullptr) {
                        q.push(left);
                    }
                    
                    auto right = now->right;
                    if (right != nullptr) {
                        q.push(right);
                    }
                }
                
                ans++;
            }
        }
        
        return ans;
    }
};

Solution 2

Solution 1的Python实现

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        ans = 0
        
        if root is not None:
            q = collections.deque([root])
            
            while q:
                numNodeLevel = len(q)
                
                while numNodeLevel:
                    
                    now = q.popleft()

                    left, right = now.left, now.right
                    if left is not None:
                        q.append(left)
                    if right is not None:
                        q.append(right)
                        
                    numNodeLevel -= 1
                    
                ans += 1
            
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值