leetcode104 二叉树的最大深度

使用迭代法的话,使用层序遍历是最为合适的,因为最大的深度就是二叉树的层数,和层序遍历的方式极其吻合。

在二叉树中,一层一层的来遍历二叉树,记录一下遍历的层数就是二叉树的深度。

class Solution {
public:
    int maxDepth(TreeNode* root) {
        queue<TreeNode*> q;
        if(root) q.push(root);
        int nums = 0;
        while(!q.empty()){
            int size = q.size();
            for(int i = 0; i < size; i++){
                TreeNode* cur = q.front();
                q.pop();
                if(cur->left) q.push(cur->left);
                if(cur->right) q.push(cur->right);
            }
            nums++;
        }
        return nums;
    }
};

方法 1:标准 DFS 递归(后序遍历)

思路:计算左子树和右子树的深度,取较大值并 +1(当前层深度)。

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int level = 0;
        if(root == nullptr) return 0;
        int left = maxDepth(root->left);
        int right = maxDepth(root->right);
        return max(left, right) + 1;
    }
};

方法 2:DFS + 传当前深度(前序遍历)

思路:在递归时维护当前深度,并更新全局最大深度。

class Solution {
private:
    int max = 0;
    void traverse(TreeNode* cur, int level){
        if(cur == nullptr) return;
        if(level > max) max = level;
        if(cur->left) traverse(cur->left, level+1);
        if(cur->right) traverse(cur->right, level+1);
    }
public:
    int maxDepth(TreeNode* root) {
        traverse(root, 1);
        return root ? max : 0;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值