• leetcode-Given a binary tree, find its minimum depth


    第一题

    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.

    返回一个二叉树的最短深度,即从根节点到叶子节点的所有路径中中,包含最少节点的那条路径上的节点个数

    public class Solution {
        public int run(TreeNode root) {
            if(root == null)
                return 0;
            int i = run(root.left);
            int j = run(root.right);
            return (i == 0 || j == 0) ? i+j+1 : Math.min(i, j)+1;
        }
    }

      这段代码是网上大神的,使用了递归的思想。

      当遇到空节点(即叶子节点的子节点)时,返回0,表示叶子节点的子树的最短深度为0(叶子节点没有子树)。对于非叶子节点,利用run函数得到其左右子树的最短深度,将其中比较短的那条子树的最短深度+1(要加上本节点)后返回,特别的,如果其左右子树中的有一条为空,则返回非空子树的最短深度+1,只是因为当存在空子树时,过此点的最小深度路径之经过非空的那条子树。当然,如果左右子树都为空,说明当前节点为叶子节,返回值为1。

  • 相关阅读:
    2
    1
    Java面试题整理二(侧重SSH框架)
    solr添加多个core
    Oracle SQL性能优化
    jQuery的$.ajax
    spring四种依赖注入方式
    通过JAXB完成Java对象与XML之间的转换
    window环境下将solr6.3部署到tomcat中
    Java面试题整理一(侧重多线程并发)
  • 原文地址:https://www.cnblogs.com/qj4d/p/7078456.html
Copyright © 2020-2023  润新知