javaee论坛

普通会员

225648

帖子

355

回复

369

积分

楼主
发表于 2017-07-27 16:11:19 | 查看: 551 | 回复: 2
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Solution

  • 题目意思就是求一二叉树的最大深度,空树的深度定义为0
  • 我们可以采用递归的方式来进行,对于空树返回0,否则返回左子树深度+1和右子树深度+1的最大值。(因为子树的深度是父亲的+1)。代码如下:
class Solution {public:    int maxDepth(TreeNode* root) {        if (!root)            return 0;        else            return max(maxDepth(root->left) + 1,maxDepth(root->right) + 1);    }};
  • 另外,上述方法其实是采用了DFS(深度优先搜索),在讨论区也看到了利用队列实现的BFS(广度优先搜索),代码如下,侵删。
int maxDepth(TreeNode *root){    if(root == NULL)        return 0;    int res = 0;    queue<TreeNode *> q;    q.push(root);    while(!q.empty())    {        ++ res;        for(int i = 0, n = q.size(); i < n; ++ i)        {            TreeNode *p = q.front();            q.pop();            if(p -> left != NULL)                q.push(p -> left);            if(p -> right != NULL)                q.push(p -> right);        }    }    return res;}

普通会员

10

帖子

318

回复

344

积分
沙发
发表于 2019-11-03 05:41:06

谢谢

普通会员

2

帖子

348

回复

360

积分
板凳
发表于 2024-05-04 05:59:02

专业抢二楼!顺便笑摸狗头(3L)

您需要登录后才可以回帖 登录 | 立即注册

触屏版| 电脑版

技术支持 历史网 V2.0 © 2016-2017