题解 | 二叉树的最小深度

二叉树的最小深度

https://www.nowcoder.com/practice/e08819cfdeb34985a8de9c4e6562e724?tpId=46&tqId=29030&rp=1&difficulty=&judgeStatus=&tags=/question-ranking

import java.util.*;


// public class TreeNode {
//     int val = 0;
//     TreeNode left = null;
//     TreeNode right = null;
// }

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int run (TreeNode root) {
        ArrayList<Integer> path = new ArrayList<>();
        // write code here
        if (root == null) {
            return 0;
        }

        DFS(root, 1, path);
        return Collections.min(path);
    }

    public void DFS(TreeNode root, int depth, ArrayList<Integer> path) {
        if (root.left != null) {
            DFS(root.left, depth + 1, path);
        }
        if (root.right != null) {
            DFS(root.right, depth + 1, path);
        }
        if (root.left == null && root.right == null) {
            path.add(depth);
        }
    }
}

全部评论

相关推荐

09-17 10:53
四川大学 C++
牛客91242815...:会写标书没有任何卵用,鉴定为横向垃圾导师的受害者
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务