博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]Minimum Depth of Binary Tree
阅读量:4355 次
发布时间:2019-06-07

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

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,2]这种情况,返回树最低高度为2。所以分两种情况,有一棵子树不在时,返回另一棵子树树高+1,否则返回矮子树高+1.

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {private:    int ret;public:    int DFS(TreeNode *root)    {        if(root==NULL) return 0;        else if(!root->left&&!root->right) return 1;        int height1=DFS(root->left);        int height2=DFS(root->right);        if(height1==0) return height2+1;        if(height2==0) return height1+1;        return min(height1,height2)+1;    }    int minDepth(TreeNode *root) {        if(root==NULL) return 0;        ret=DFS(root);        return ret;    }};

  

转载于:https://www.cnblogs.com/Rosanna/p/3459306.html

你可能感兴趣的文章
<authentication> 元素
查看>>
svn向服务器添加新建文件夹
查看>>
iphone UI 开发教程
查看>>
简单选项卡加圆角
查看>>
soritong MP3播放器缓冲区溢出漏洞分析
查看>>
17.10.24 数据最水的一次考试
查看>>
python_SMTP and POP3
查看>>
lambda匿名函数
查看>>
js常用方法
查看>>
建造者模式
查看>>
Spring入门教程:通过MyEclipse开发第一个Spring项目
查看>>
【转】你可能不知道的Shell
查看>>
廖雪峰Java1-2程序基础-1基本结构
查看>>
golang下的grpc
查看>>
1. 自动化运维系列之Cobbler自动装机
查看>>
ASP.NET MVC Model绑定(二)
查看>>
一步一步写算法(之hash表)
查看>>
漫谈并发编程(一) - 并发简单介绍
查看>>
JDBC连接MySQL数据库及演示样例
查看>>
System.currentTimeMillis();
查看>>