leetcode刷题日记——Maximum Depth of Binary Tree
2015-12-17 19:42
253 查看
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.
Subscribe to see which companies asked this question
问题分析:问题比较简单,目的是求二叉数的最大深度。可以采用递归的办法,递归条件是二层之间的高度相差1,因为最终要返回最大深度,因此分别对左右子树分别递归,然后将最终结果返回即可,不过这里没有考虑最优解,留待以后优化。代码如下:
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Subscribe to see which companies asked this question
问题分析:问题比较简单,目的是求二叉数的最大深度。可以采用递归的办法,递归条件是二层之间的高度相差1,因为最终要返回最大深度,因此分别对左右子树分别递归,然后将最终结果返回即可,不过这里没有考虑最优解,留待以后优化。代码如下:
/** * 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==NULL) return 0; int left=maxDepth(root->left)+1; int right=maxDepth(root->right)+1; return left>right?left:right; } };
相关文章推荐
- 多表利用DIH批量导入数据并建立索引注意事项
- Beta版本冲刺———第七天
- 3678: wangxz与OJ
- [笔记]修改mac终端命令行前缀的显示
- C++11引用限定符
- [Linux]ubuntu下共享文件夹密码设置和重置-smbpasswd -a user
- 中断
- Detours信息泄漏漏洞
- 网页去重(一)简介
- visual studio下实现图形函数调用
- 黑马程序员--Java编程之反射篇
- 如何在Allegro中添加中文汉字
- 解决在Fragment中不能自动弹出软键盘的问题
- CAAnimation动画/CAAnimation Group
- OC
- poj 1724 ROADS 最短路
- Daily Scrum 12.17
- 修改 SVN 提交 LOG 默认编辑器
- Softmax回归
- Android-->RxJava/RxAndroid 入门初体验