首页 > 代码库 > leetcode 104. Maximum Depth of Binary Tree

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