二叉树结点最小深度求解算法(Java语言描述)

问题描述

给定二叉树,找到其最小深度。
最小深度是沿着从根结点到最近的叶子结点的最短路径的节点数。

分析

递归实现即可:

  • 当前结点为null,表示到达了叶子结点,终止递归,返回0。
  • 当前结点非null,表示还没到达叶子结点,
    • 左儿子空,右儿子非空,就深度+1并以当前结点为根结点,递归右子树;
    • 右儿子空,左儿子非空,就深度+1并以当前结点为根结点,递归左子树;
    • 除此之外,左右都非空,就深度+1并返回左右深度的min()值。

编程实现

public class Solution {
    public int getDepth(TreeNode root) {
        if(root == null) {
            return 0;
        } else if(root.left == null && root.right != null) {
           return getDepth(root.right)+1;
        } else if(root.left != null && root.right == null) {
            return getDepth(root.left)+1;
        }
        return Math.min(getDepth(root.left), getDepth(root.right))+1;
    }
}
发布了570 篇原创文章 · 获赞 1179 · 访问量 36万+

猜你喜欢

转载自blog.csdn.net/weixin_43896318/article/details/104460178
今日推荐