加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

【一天一道LeetCode】#104. Maximum Depth of Binary Tree

发布时间:2020-12-13 21:10:11 所属栏目:PHP教程 来源:网络整理
导读:1天1道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (1)题目 来源:https://leetcode.com/problems/maximum-depth-of-binary-tree/ Given a binary tree,find

1天1道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(1)题目

来源:https://leetcode.com/problems/maximum-depth-of-binary-tree/

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.

(2)解题

题目大意:求2叉树的最大深度
解题思路:采取深度优先搜索,很容易求出最大深度

/** * 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 max;//用来保存最大深度值 int maxDepth(TreeNode* root) { max = 0; dfsTree(root,0);//深度优先搜索递归 return max; } void dfsTree(TreeNode* root,int dep) { if(dep>max) max=dep;//记录最大深度值 if(root==NULL) return; dfsTree(root->left,dep+1);//遍历左子树 dfsTree(root->right,dep+1);//遍历右子树 } };

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读