LC104 二叉树的最大深度

本题给定的函数参数只有结点指针,由于无法传入当前节点的深度,无法使用自顶向下的方法求解

递归解法-自底向上

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

如果参数可以多一个int类型,则可以使用自顶向下的方法,直接调用maxDepth(root, 0)即可

递归解法-自顶向下

class Solution {
private:
    int ans;
public:
    int maxDepth(TreeNode* root, int dep) {
        if(!root->left && !root->right)
            return ans > (dep + 1) ? ans : (dep + 1);
        maxDepth(root->left, dep + 1);
        maxDepth(root->right, dep + 1);
    }
};

非递归解法

也可以使用层次遍历来解决这个问题,参考之前层次遍历的写法即可

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int res = 0;
        if(root == nullptr)
            return res;
        queue<TreeNode*> level;
        level.push(root);
        while(!level.empty()){
            int size = level.size();
            for(int i = 0; i < size; i ++){
                TreeNode* nowNode = level.front();
                if(nowNode->left != nullptr) 
                    level.push(nowNode->left);
                if(nowNode->right != nullptr) 
                    level.push(nowNode->right);
                level.pop();
            }
            res++;
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/imagineincredible/p/13321671.html