【问题】给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

/ \

/ \
7 返回它的最大深度 3 。

【DFS解法】

我们使用栈结构来储存每个节点root以及该节点的深度deep,由于对tuple的使用还不太熟练,需要多练习,一次使用tuple来讲树结构体指针和对应的整型变量深度。从根节点开始遍历,首先一直遍历左子节点,并将节点压入栈中,如果左子节点为空,则从栈中弹出,并开始遍历弹出节点的右子节点。这个过程也就相当于回溯了,回到上一级去。

**
* 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 == nullptr) return ;
stack<tuple<TreeNode*, int>> sta;
int maxdeep = ;
int deep = ;
while(!sta.empty() || root){
while(root){
sta.push(make_tuple(root, deep+));
deep++;
root = root->left;
}
tie(root, deep) = sta.top();
if(maxdeep < deep) maxdeep = deep;
sta.pop();
root = root->right;
}
return maxdeep;
}
};

【BFS解法】

这个其实质就是层次遍历,使用队列来储存树节点,并使用size变量记录每次节点的数量,在一次循环中,处理掉一层的节点,具体做法:将某一层所有节点的子节点压入队列后,并将所有的节点移除队列。
在处理某一层的树节点的同时,使用count变量记录处理的层数。即为最大深度!

/**
* 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 == nullptr){
return ;
}
queue<TreeNode*> que;
que.push(root);
int count = ;
while(que.size() != ){
int size = que.size(); while(size--){
TreeNode* tmp = que.front();
if(tmp->left != nullptr) que.push(tmp->left);
if(tmp->right != nullptr) que.push(tmp->right);
que.pop();
}
count++;
}
return count;
}
};

最新文章

  1. CSS 高级布局技巧
  2. bash/shell编程学习(2)
  3. 外部函数test显示的返回内部函数add的调用
  4. Open any local folder/file in IE11 (and more) using MSHH
  5. 李洪强漫谈iOS开发[C语言-049]-猜数字游戏
  6. 雷军V5,米3横空出世
  7. ExtJS学习之路第三步:理解引擎之下,ExtJS4中的类
  8. Android Study ING
  9. algorithm@ Matrix fast power
  10. canvas动画:自由落体运动
  11. java接受安卓及ios App上传的图片,并保存到阿里OSS
  12. bootstrap 失效的原因
  13. python 入门基础24 元类、单例模式
  14. 字节顺序:高位优先(big-endian)和低位优先(little-endian)
  15. AS_简单的开始
  16. STM32 通用定时器相关寄存器
  17. 为什么 c = tf.matmul(a, b) 不立即执行矩阵乘法?
  18. golang struct转map
  19. Spring Data MongoDB 模糊查询
  20. IIS添加域名

热门文章

  1. HttpServletRequest 或 HttpServletResponse显示红色,需引用的依赖包:servlet-api.jar
  2. 关于页面跳转之后获取不到session数据的问题
  3. greenplum 存储过程 输出信息
  4. 2-10 就业课(2.0)-oozie:7、job任务的串联
  5. CRC校验算法详解
  6. 清北学堂例题 LUOGU2523【HAOI2011】problem c
  7. 洛谷 P3801 红色的幻想乡
  8. 020、Java中字母大小写转换
  9. java.lang.IllegalStateException: Active Spring transaction synchronization or active JTA transaction with specified [javax.transaction.TransactionManager] required
  10. angularJS 服务