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

前言

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

题目传送门: 点击此处

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

递归方式

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

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

迭代方式

DFS

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

public int maxDepth(TreeNode root) {
    if(root == null) {
        return 0;
    }
    Stack<TreeNode> stack = new Stack<>();
    Stack<Integer> value = new Stack<>();
    stack.push(root);
    value.push(1);
    int max = 0;
    while(!stack.isEmpty()) {
        TreeNode node = stack.pop();
        int temp = value.pop();
        max = Math.max(temp, max);
        if(node.left != null) {
            stack.push(node.left);
            value.push(temp+1);
        }
        if(node.right != null) {
            stack.push(node.right);
            value.push(temp+1);
        }
    }
    return max;
}

BFS

public int maxDepth(TreeNode root) {
    if(root == null) {
        return 0;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    int count = 0;
    while(!queue.isEmpty()) {
        int size = queue.size();
        while(size > 0) {
            TreeNode node = queue.poll();
            size--;
            if(node.left != null) {
                queue.offer(node.left);
            }
            if(node.right != null) {
                queue.offer(node.right);
            }
        }
        count++;
    }
    return count;
}
发布了151 篇原创文章 · 获赞 148 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq1515312832/article/details/104259983