【第一周algorithm1】-minimum-depth-of-binary-tree

=============算法题目=============

Give a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from root node down to the nearest leaf node.

=================================

递归(DFS):

方法1:

public int run(TreeNode root) {
    //1:空结点
    if (root == null)
        return 0;
    //2:左右子树都为空,返回root的深度为1
    if (root.left == null && root.right == null)
        return 1;
    //3:左或者右子树为空,则返回相应的非空子树最小值+1
    if (root.left == null && root.right != null)
        return 1 + run(root.right);
    if (root.right == null && root.left != null)
        return 1 + run(root.left);
    //4:如果左右子树都不为空,则返回左右子树中最小值
    return Math.min(run(root.left) + 1, run(root.right) + 1);
}

方法2:

public int run(TreeNode root) {
    //1:空结点
    if (root == null)
        return 0;
    //2:左右子树都为空或者有一个非空的情况,返回root的深度为1
    int l = run(root.left);
    int r = run(root.right);
    if (l == 0 || r == 0)
        return l + r + 1;
    //3:如果左右子树都不为空,则返回左右子树中最小值
    return Math.min(l, r) + 1;
}


迭代(BFS):

方法1:

public int runLevelTraverse(TreeNode root){
    //1:如果树为空,返回0
    if (root == null)
        return 0;
    //2:如果只有一个根结点,返回1(此处可去掉,因为此处包含在下面)
    if (root.right == null && root.left == null)
        return 1;
    //3:否则,用层次遍历来寻找第一个leaf node ,则为最短路径
    int depth = 0;
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while (!queue.isEmpty()){
        int size = queue.size();
        depth++;
        for (int i = 0; i < size; i++){
            TreeNode curNode = queue.poll();
            if (curNode.left == null && curNode.right == null)
                return depth;
            if (curNode.left != null)
                queue.offer(curNode.left);
            if (curNode.right != null)
                queue.offer(curNode.right);
        }
    }
    return 0;
}


方法2:

public int runLevelTraverse(TreeNode root){
    //1:如果树为空,返回0
    if (root == null)
        return 0;
    //2:否则,用层次遍历来寻找第一个leaf node ,则为最短路径
    ArrayList<TreeNode> list = new ArrayList<>();
    //根入队列,此处使用arrayList模拟队列功能
    list.add(root);
    int depth = 1;
    //curr指向当前层的第一个结点,last指向下一层的第一个结点
    int cur = 0, last;
    while (cur < list.size()){
        last = list.size();
        //遍历当前层,如果有叶子结点则返回depth,否则depth+1继续遍历
        while (cur < last){
            TreeNode curNode = list.get(cur);
            if (curNode.left == null && curNode.right == null)
                return depth;
            if (curNode.left != null)
                list.add(curNode.left);
            if (curNode.right != null)
                list.add(curNode.right);
            cur++;
        }
        depth++;
    }
    return depth;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值