leetcode 104. Maximum Depth of Binary Tree

Posted StrongYaYa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 104. Maximum Depth of Binary Tree相关的知识,希望对你有一定的参考价值。

题目描述:

递归

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

循环

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL)
            return 0;
        queue<TreeNode *>  qu;
        int ret = 0;
        qu.push(root);
        while(!qu.empty()){
            ret++;
            for(int i = 0,n = qu.size() ; i < n; i++){
                TreeNode *tmp = qu.front();
                qu.pop();
                if(tmp->left != NULL)
                    qu.push(tmp->left);
                if(tmp->right != NULL)
                    qu.push(tmp->right);
            }
        }
        return ret;
    }
};

 

以上是关于leetcode 104. Maximum Depth of Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode104. Maximum Depth of Binary Tree

leetcode104-Maximum Depth of Binary Tree

Leetcode刷题记录[python]——104 Maximum Depth of Binary Tree

LeetCode 104. Maximum Depth of Binary Tree

[Lintcode]97. Maximum Depth of Binary Tree/[Leetcode]104. Maximum Depth of Binary Tree

LeetCode 104 Maximum Depth of Binary Tree