• niubility
    2019-01-03
    最小深度java的 DFS写法:
    class Solution {
        public int minDepth(TreeNode root) {
            if (root == null) return 0;

            if (root.right == null){
                return minDepth(root.left) + 1;
            }

            if (root.left == null){
                return minDepth(root.right) + 1;
            }

            return Math.min(minDepth(root.left) + 1,minDepth(root.right) + 1);
        }
    }
    展开

    作者回复: 👍🏻👍🏻

    
     4
  • 唯她命
    2018-11-29
    我觉得还可以优化,如果左子树深度为1,而右子树的深度为10000,那么这种方法需要把右子树10000的深度全部递归完,其实没有必要

    作者回复: 对的,可以还可以持续优化。最好的办法是 bfs

    
     2
  • 心有薇蔷
    2019-08-18
    左子树为空时,应该返回的最小深度不是1吗,为什么是1+右子树深度?
     2
     1
  • 林先生
    2019-11-10
    为什么作者说不建议用递归,最后写出来的代码是用递归

    作者回复: 没有不建议递归,而是提醒在递归的时候注意重复计算和复杂度。

    
    
  • xuhaohao
    2019-04-03
    ######python 写的广度优先的代码
    class Solution:
        def maxDepth(self, root: TreeNode) -> int:
            if not root: return 0
            
            queue=[]
            visited=[]
            queue.append(root)
            length=0
            while queue:
                len1=len(queue)
                length+=1
                for i in range(len1):
                    node=queue.pop(0)
                    if node.left:
                        queue.append(node.left)

                    if node.right:
                        queue.append(node.right)
            return length
    展开

    作者回复: Cool!

    
    
  • nullz
    2019-03-12
    是不是可以理解为递归=dfs

    作者回复: 可以大致这么理解,但肯定需要具体问题具体分析。

    
    
  • 劲奇
    2019-01-13
    老师你好,有一点我不太明白:求最大深度时
    public int maxDepth(TreeNode root) {
            return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
        }这样写就正确;
    public int maxDepth(TreeNode root) {
            //return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
            if(root==null){
                return 0;
            }else{
            return Math.max(maxDepth(root.left),maxDepth(root.left))+1;
            }
        }这样写结果就不对。
    展开

    作者回复: 仔细看:有typo。你用了两个left

    
    
  • 怪兽们的博物馆
    2019-01-05
    请问老师,BFS 的话,如何知道当前在哪一层?谢谢。

    作者回复: 两个办法: 1 记下每层的节点数,类似leetcode的按层打印数的节点的那个题目的代码 2 或者也可以在queue里加入一个分隔每层节点的 dummy node.

    
    
我们在线,来聊聊吧