博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode:Minimum Depth of Binary Tree
阅读量:4180 次
发布时间:2019-05-26

本文共 1083 字,大约阅读时间需要 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.递归

class Solution {public:    int run(TreeNode *root) {        if(root==NULL)            return 0;        int depthl=run(root->left);        int depthr=run(root->right);                 if(depthl==0&&depthr==0)            return 1;        if(depthl==0)            depthl=INT_MAX;//没有左节点一定不是该路径        if(depthr==0)            depthr=INT_MAX;        return min(depthl,depthr)+1;    }};
2.非递归

按广度优先遍历(按层次遍历),若某一层出现了叶节点就返回其深度。

int run(TreeNode *root) {    queue
> q; if(root == NULL) return 0; q.push(make_pair(root,1)); while(!q.empty()){ pair
cur = q.front(); q.pop(); if(!cur.first->left && !cur.first->right) return cur.second; if(cur.first->left) q.push(make_pair(cur.first->left,cur.second+1)); if(cur.first->right) q.push(make_pair(cur.first->right,cur.second+1)); }}
其中用到了STL容器类。

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

你可能感兴趣的文章
android一行代码实现沉浸式布局效果
查看>>
json, recyclerView问题
查看>>
cmake处理多源文件目录的方法
查看>>
Service Intent must be explicit
查看>>
android studio SDK开发
查看>>
studio 统计代码的行数
查看>>
字符数组和16进制互换
查看>>
PHP项目中出现致命错误: Class 'Redis' not found
查看>>
There is no tracking information for the current branch.
查看>>
fatal: refusing to merge unrelated histories
查看>>
Git命令还原未提交的变更
查看>>
Linux系统中环境变量的配置
查看>>
Linux系统中配置脚本程序开机启动
查看>>
让Linux系统上的nginx支持php程序
查看>>
源码编译安装LNMP环境之Nginx篇
查看>>
源码编译安装LNMP环境之PHP篇
查看>>
Linux中rpm工具使用教程
查看>>
Linux中yum工具使用教程
查看>>
C++字符串函数
查看>>
mknod详解
查看>>