zoukankan      html  css  js  c++  java
  • 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.ECMAScript 5.0
    1.Javascript简介
    9.定位
    HDU2032 杨辉三角
    HDU2058 The sum problem
    HDU2091 空心三角形
    HDU1166 敌兵布阵(树状数组模板题)
    HDU2049 不容易系列之(4)——考新郎
    Python网络爬虫与信息提取(三)(正则表达式的基础语法)
    HDU6576 Worker
  • 原文地址:https://www.cnblogs.com/qj4d/p/7078456.html
Copyright © 2011-2022 走看看