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

    这道题其实就是一道简单的递归,可是在写的时候还是遇到一点小问题,感觉还是对递归不够熟悉,还无法直接捋出这个递归的结构。

    总结一下   用递归实现一个问题的思考思路:

    1.先用语言描述出来,就是描述出想用这个递归来实现什么,考虑一层递归需要实现什么功能,嵌套起来才能实现整个问题。

    2.关键是想的过程, 递归函数的基本功能模板   在子问题已经解决的情况下,使用子问题的返回值来结合自己当前情况,返回一个值给自己的父级

    3.还有一个就是递归的返回情况,最边界情况下的处理情况

  • 相关阅读:
    技术笔记3
    技术笔记2 jetty jboss
    技术笔记1前台
    日常笔记4
    日常笔记3
    日常笔记2
    日常笔记
    C语言——结构体
    用Java原子变量的CAS方法实现一个自旋锁
    Java中处理Linux信号量
  • 原文地址:https://www.cnblogs.com/tobemaster/p/5874637.html
Copyright © 2011-2022 走看看