首页 > 其他 > 详细

leetcode 104. Maximum Depth of Binary Tree

时间:2017-04-26 15:36:33      阅读:175      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享

递归

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

原文:http://www.cnblogs.com/strongYaYa/p/6768424.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!