【LeetCode】104. Maximum Depth of Binary Tree 二叉树的深度 DFS BFS 递归方式 迭代方式 JAVA

谁借莪1个温暖的怀抱¢ 2021-06-10 20:37 377阅读 0赞

前言

这次的题目是二叉树的深度遍历,总体上来说吧,难度没有那么大,可是我就是再迭代的地方爬不出来了,有些题解也没有注释,讲解的也不是很清楚,所以就看起来有点麻烦

题目传送门: 点击此处

题目截图:
在这里插入图片描述

递归方式

  1. public int maxDepth(TreeNode root) {
  2. return root == null ? 0 : Math.max(maxDepth(root.left) + 1, maxDepth(root.right) + 1);
  3. }

PS:
虽然有人不是很理解代码为什么要写成一行,但是我觉得写成一行很得劲儿
虽然会被嫌弃,但是我还是想这么干
虽然我也嫌弃别人这么些,但是我也还是像这样写

迭代方式

DFS

不要吐槽我,注释稍后添加!!!!!!!!!!!!!!!!!!!!

  1. public int maxDepth(TreeNode root) {
  2. if(root == null) {
  3. return 0;
  4. }
  5. Stack<TreeNode> stack = new Stack<>();
  6. Stack<Integer> value = new Stack<>();
  7. stack.push(root);
  8. value.push(1);
  9. int max = 0;
  10. while(!stack.isEmpty()) {
  11. TreeNode node = stack.pop();
  12. int temp = value.pop();
  13. max = Math.max(temp, max);
  14. if(node.left != null) {
  15. stack.push(node.left);
  16. value.push(temp+1);
  17. }
  18. if(node.right != null) {
  19. stack.push(node.right);
  20. value.push(temp+1);
  21. }
  22. }
  23. return max;
  24. }

BFS

  1. public int maxDepth(TreeNode root) {
  2. if(root == null) {
  3. return 0;
  4. }
  5. Queue<TreeNode> queue = new LinkedList<>();
  6. queue.offer(root);
  7. int count = 0;
  8. while(!queue.isEmpty()) {
  9. int size = queue.size();
  10. while(size > 0) {
  11. TreeNode node = queue.poll();
  12. size--;
  13. if(node.left != null) {
  14. queue.offer(node.left);
  15. }
  16. if(node.right != null) {
  17. queue.offer(node.right);
  18. }
  19. }
  20. count++;
  21. }
  22. return count;
  23. }

发表评论

表情:
评论列表 (有 0 条评论,377人围观)

还没有评论,来说两句吧...

相关阅读