博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
给定二叉树求最小深度
阅读量:4048 次
发布时间:2019-05-25

本文共 857 字,大约阅读时间需要 2 分钟。

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.

关键点:

1)必须注意考虑左孩子或者右孩子为空的情况。

/**

 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool    isleaf(TreeNode *node)
        {
            if(NULL ==  node)
                return  false;
            if((NULL ==  node->left)    &&  (NULL   ==  node->right))
                return  true;
            else
                return  false;
        }
    int minDepth(TreeNode *root) {
        if(NULL ==  root)
            return  0;
        if(isleaf(root))
            return  1;
        if(NULL ==  root->left)
            return  1   +   minDepth(root->right);
        if(NULL ==  root->right)
            return  1   +   minDepth(root->left);
        if((1+minDepth(root->left))   <=  (1    +   minDepth(root->right)))
            return  1   +  minDepth(root->left);
        else
            return  1   +  minDepth(root->right);
    }
};

转载地址:http://cpbci.baihongyu.com/

你可能感兴趣的文章
8.X版本的node打包时,gulp命令报错 require.extensions.hasownproperty
查看>>
Jenkins 启动命令
查看>>
Maven项目版本继承 – 我必须指定父版本?
查看>>
通过C++反射实现C++与任意脚本(lua、js等)的交互(二)
查看>>
利用清华镜像站解决pip超时问题
查看>>
微信小程序开发全线记录
查看>>
CCF 分蛋糕
查看>>
解决python2.7中UnicodeEncodeError
查看>>
小谈python 输出
查看>>
Django objects.all()、objects.get()与objects.filter()之间的区别介绍
查看>>
python:如何将excel文件转化成CSV格式
查看>>
机器学习实战之决策树(一)
查看>>
机器学习实战之决策树二
查看>>
[LeetCode By Python]7 Reverse Integer
查看>>
[leetCode By Python] 14. Longest Common Prefix
查看>>
[LeetCode By Python]121. Best Time to Buy and Sell Stock
查看>>
[LeetCode By Python]122. Best Time to Buy and Sell Stock II
查看>>
[LeetCode By Python]125. Valid Palindrome
查看>>
[LeetCode By Python]136. Single Number
查看>>
Android/Linux 内存监视
查看>>