码迷,mamicode.com
首页 > 其他好文 > 详细

104 Maximum Depth of Binary Tree 二叉树的最大深度

时间:2018-04-04 21:19:02      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:案例   problem   最长路   cpp   路径   solution   https   一个   ini   

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶节点的最长路径上的节点数。
案例:
给出二叉树 [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
返回最大深度为 3 。
详见:https://leetcode.com/problems/maximum-depth-of-binary-tree/description/

方法一:非递归

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root)
        {
            return 0;
        }
        queue<TreeNode*> que;
        que.push(root);
        int i=1;
        int depth=0;
        while(!que.empty())
        {
            root=que.front();
            que.pop();
            --i;
            if(root->left)
            {
                que.push(root->left);
            }
            if(root->right)
            {
                que.push(root->right);
            }
            if(i==0)
            {
                i=que.size();
                ++depth;
            }
        }
        return depth;
    }
};

 方法二:递归

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root)
        {
            return 0;
        }
        int left=maxDepth(root->left);
        int right=maxDepth(root->right);
        return max(left,right)+1;
    }
};

 

104 Maximum Depth of Binary Tree 二叉树的最大深度

标签:案例   problem   最长路   cpp   路径   solution   https   一个   ini   

原文地址:https://www.cnblogs.com/xidian2014/p/8718237.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!