104. Maximum Depth of Binary Tree
来源:互联网 发布:淘宝为什么分数低 编辑:程序博客网 时间:2024/05/21 21:43
104. Maximum Depth of Binary Tree
容易想到两种思路,深度优先搜索(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+1):(r+1);//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; }};
0 0
- [LeetCode]104.Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 【LeetCode】104.Maximum Depth of Binary Tree
- [Leetcode] 104. Maximum Depth of Binary Tree
- LeetCode --- 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- leetCode 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree LeetCode
- 104. Maximum Depth of Binary Tree LeetCode
- 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- leetcode:104. Maximum Depth of Binary Tree
- java 二进制 十进制 十六进制数据类型转换
- ionic基础概念
- 如何表示一个算法(笔记)
- VirtualBox虚拟机网络设置
- iOS线程通信
- 104. Maximum Depth of Binary Tree
- 免费帮做网页设计,想要多实践一下,巩固自己的基础。
- 方法锁和静态方法锁的区别
- Mat类详解(三)
- 常见锁的区别及适用场景
- Riak - 背景篇(2)
- Xamarin安装信息
- 你真的会用Fragment了么?-Fragment解析
- c++ container