zoukankan      html  css  js  c++  java
  • leetcode 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.

    Subscribe to see which companies asked this question

    刚开始写的代码是这样的。

            if(root==NULL) return 0;
            return min(mindeep(root->right)+1,mindeep(root->left)+1);

    看出问题了吧,这段代码“看上去”是正确的,但是对于这种结构

                  1
                 / 
                2 

                  5
                 / 
                4   8
               /     
              11      4
    对于以上两种结构都是计算错误,因为第一种结构它把根节点自己也看做一条路径,这样是不对的。
    所以要做判断,当根节点只有一条路径的时候,只计算一条路径的长度,而不是继续选最小了。
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int minDepth(TreeNode* root){
            if(root==NULL) return 0;
            if(root->left&&root->right) return min(minDepth(root->left)+1,minDepth(root->right)+1);
            else if(root->left==NULL||root->right==NULL) return max(minDepth(root->right)+1,minDepth(root->left)+1);
        }
    
    };
    
    
    


  • 相关阅读:
    day23
    day22
    day21
    day20
    小程序 组件操作
    jmeter安装使用一
    小程序登录操作
    Django ORM DateTimeField 时间误差8小时问题
    小程序初始篇
    ADB命令
  • 原文地址:https://www.cnblogs.com/LUO77/p/5032827.html
Copyright © 2011-2022 走看看