zoukankan      html  css  js  c++  java
  • Lintcode---二叉树的最小深度

    给定一个二叉树,找出其最小深度。

    二叉树的最小深度为根节点到最近叶子节点的距离。
    样例

    给出一棵如下的二叉树:

            1

         /      

       2       3

              /    

            4      5  

    这个二叉树的最小深度为 2

    思路:本来是很简单的一道题目,使用递归方法很容易求解,思路也清晰,但很久没AC。
             
         反思,在考虑的时候不要被绕进去,从大的方面考虑,思路正确就可以。
         另外,在debug时,直接通过测试用例来模拟程序过程,快速找到问题所在。

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
    public:
        /**
         * @param root: The root of binary tree.
         * @return: An integer
         */
        /*
        思路:本来是很简单的一道题目,使用递归方法很容易求解,思路也清晰,但很久没AC。
             
              反思,在考虑的时候不要被绕进去,从大的方面考虑,思路正确就可以。
              另外,在debug时,直接通过测试用例来模拟程序过程,快速找到问题所在。
        */
        int minDepth(TreeNode *root) {
            // write your code here
            
            if(root==NULL){
                return 0;
            }
        
    
            if(root->right==NULL){
                return minDepth(root->left)+1;
            }
            if(root->left==NULL){
                return minDepth(root->right)+1;
            }
            return min(minDepth(root->left),minDepth(root->right))+1;
        }
    };
    
  • 相关阅读:
    node同时验证手机号和座机号
    导入excle到服务器时候删除服务器历史数据
    杂七杂八
    c# 导出表格 api
    c# 导出表格
    element split 将多个单号分隔
    vue 前台传后台
    vue.js 使用时间组件 日期少一天的问题
    layui 文字滚动
    CRT&&EXCRT学习笔记
  • 原文地址:https://www.cnblogs.com/Allen-rg/p/7088738.html
Copyright © 2011-2022 走看看