104. Maximum Depth of Binary Tree
2016-04-19 10:31
363 查看
104. Maximum Depth of Binary Tree
容易想到两种思路,深度优先搜索(DFS)和广度优先搜索(BFS):
思路一(DFS):
思路二(BFS):
容易想到两种思路,深度优先搜索(DFS)和广度优先搜索(BFS):
思路一(DFS):
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)//1.递归结束条件 return 0; int l=maxDepth(root->left);//2.左子树深度 int r=maxDepth(root->right);//2.右子树深度 return l>r?l:r;//3.递归操作 } };
思路二(BFS):
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int maxDepth(TreeNode* root) { queue< TreeNode * > que;//引入队列 que.push(root); int num=1;//记录每一层的节点数 int depth=0;//记录树的深度 while(!que.empty()) { TreeNode* node=que.front(); que.pop(); num--; if(node->left!=NULL) que.push(node->left); if(node->right!=NULL) que.push(node->right); if(num==0)//一层遍历结束 { depth++; num=que.size(); } } return depth; } };
相关文章推荐
- 常见锁的区别及适用场景
- 你真的会用Fragment了么?-Fragment解析
- windows mongodb 安装
- asp.net发布到IIS中出现错误:处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler”
- 页面向下滑动实现div显示和隐藏
- android 禁用点击事件的三个属性
- iOS线程通信
- Mat类详解(三)
- 273. Integer to English Words
- 对我有价值的文章记录
- Java中的Constants类
- update_TypeError
- 英译中批量翻译
- linux 红帽6.5修改root密码
- ionic基础概念
- Mybatis学习记录(五)--整合spring开发Dao
- gdb
- java线程
- SQLite笔记
- 研发过程中动态看板的使用推广