Leetcode算法题 minimum depth of binary tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013276277/article/details/81350008

题目描述:

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

思路:明确一点,不要读错题目意思,不是要你求出二叉树的最小深度(当然也是用到了计算二叉树深度的方法,),而是从根节点到叶子节点的最短距离(一定要是叶子节点),叶子节点就是左子树和右子树都为空的节点。知道叶子节点,那么我们就可以开始用最笨的方法来做了,先遍历的树的叶子节点,然后开始计数。当没找到叶子节点是,需要确定左右子树的情况分别做处理:
1、左子树不为空,右子树不空,返回左子树的深度+1;

2、右子树不为空,左子树为空,返回右子树的深度+1;

3、左右子树都不为空,返回两颗子树的最小深度+1;

说明一下,我这是笨方法,我需要去遍历所有的节点才能获得我最终的结果。你可以是广度优先遍历方法或者层序遍历,找到第一个叶子节点,就可以确定最短距离了。

笨方法如下:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int run(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return getDepth(root);
    }
    
    public int getDepth(TreeNode root) {
        if (root.left == null && root.right == null) {
            return 1;
        } else {
            int left = 0;
            int right = 0;
            if (root.left != null && root.right == null) {
                return getDepth(root.left) + 1;
            } else if (root.right != null && root.left == null) {
                return getDepth(root.right) + 1;
            } else {
                left = getDepth(root.left);
                right = getDepth(root.right);
                return (left > right ? right : left) + 1;
            }
           
        }
    }
}

下面,重点来了,层次遍历来找出根节点到叶子节点的最短距离,思路就是,先判断两个特殊情况(自己看代码能理解),然后找一个队列来实现层次遍历,只是在层次遍历的时候判断节点是否为叶子节点,是就返回此时的遍历深度。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
    public int run(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        int depth = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (queue.size() > 0) {
            int len = queue.size();
            depth++;
            for (int i = 0; i < len; i++) {
                TreeNode node = queue.poll();
                if (node.left == null && node.right == null) return depth;
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right); 
            }
        }
        return depth;
    }
}

猜你喜欢

转载自blog.csdn.net/u013276277/article/details/81350008