104. Maximum Depth of Binary Tree
2016-05-23 18:04
369 查看
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.
Only one line code.
int maxDepth(TreeNode *root)
{
return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;
}
Calculate the count of the last level.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
1. Depth-first-search
Only one line code.int maxDepth(TreeNode *root)
{
return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;
}
2. Breadth-first-search
Calculate the count of the last level.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; }
相关文章推荐
- 责任链模式(Chain of Responsibility)的标准版
- Validation of viewstate MAC failed.的解决方法
- Some tips of wmi scripting in jscript (1)
- Bin 和 App_Code 文件夹介绍
- c# in depth的泛型实现实例代码
- Java设计模式之责任链模式(Chain of Responsibility模式)介绍
- Git使用小坑 Out of memory错误的解决方法
- identifier of an instance of com.edu.zidonghua.po.TbUser was altered from 2 to null
- The art of software testing翻译--第一章
- Check out the top five articles of 2006
- Security functions of common Active Directory tools
- 不想每次都到: /usr/local/mysql/bin
- Overview of Siebel Application Integration
- 如何安装.bin文件?
- Get the SID of an Active Directory User
- java反射getConstructor()[0].newInstance(params)报wrong number of args的错误
- Exchange bin先常用工具
- sh脚本异常:/bin/sh^M:bad interpreter: No such file or directory
- configure: error: cannot run /bin/sh config/config.sub
- 数学符号,不常用的时候参考一下…