zoukankan      html  css  js  c++  java
  • Minimum Depth of Binary Tree

    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.

    求二叉树的最小深。其实有个题目是求最大深度,题目类似,但是有一点点的改变。

    因为是最小深度,所以必须增加一个叶子判断(因为如果一个节点如果只有左子树或者右子树,我们不能取它的左右子树中小的作为深度,因为那样会是0,我们只有在叶子结点才能判断深度,而在求最大深的时候因为一定会取最大的那个所以不会有这个问题。)这道题有递归和非递归两种办法。

    递归解法是比较常规的思路:

    /**
     * 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;
            }
            if(root.left == null && root.right == null){
                return 1;
            }
            if(root.left == null){
                return run(root.right)+1;
            }
            if(root.right == null){
                return run(root.left)+1;
            }
            return Math.min(run(root.left),run(root.right))+1;
        }
    }

    非递归的方法暂时不想写。

  • 相关阅读:
    -webkit-line-clamp 多行文字溢出...
    整理一些知识碎片...
    localstorage sessionstorage和cookie的区别
    数据结构 --- Set
    Iterator(遍历器)
    ES6数组方法 -- reduce()
    ES6 -- 展开运算符
    Centos7 + Oracel 18c
    Mysql 查询返回大量数据导致内存溢出
    github的安装和使用
  • 原文地址:https://www.cnblogs.com/LoganChen/p/8085801.html
Copyright © 2011-2022 走看看