LeetCode 111: Minimum Depth of Binary Tree
来源:互联网 发布:上古卷轴5梦璃捏脸数据 编辑:程序博客网 时间:2024/05/16 03:07
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.
解题思路
思路一:采用递归的思想,分别求左右子树的最小高度;然后返回最小高度加1(注意,需要特别考虑只有一个子女的情况)。代码如下:
/** * 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; int leftH = minDepth(root->left); int rightH = minDepth(root->right); if (leftH == 0) return rightH + 1; if (rightH == 0) return leftH + 1; return min(leftH, rightH) + 1; }};
思路二:对二叉树进行按层遍历,如果在某一层发现了一个叶子节点,那么就找到了最小深度,此时返回当前深度即可。代码如下:
/** * 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; int height = 0; queue<TreeNode *> nodeQueue; nodeQueue.push(root); while (!nodeQueue.empty()) { height++; int levelSize = nodeQueue.size(); for (int i = 0; i < levelSize; ++i) { TreeNode *front = nodeQueue.front(); if (front->left == NULL && front->right == NULL) { // 在某一层发现了一个叶子节点,那么就找到了最小深度 return height; } nodeQueue.pop(); if (front->left != NULL) nodeQueue.push(front->left); if (front->right != NULL) nodeQueue.push(front->right); } } }};
0 0
- LeetCode(111)Minimum Depth of Binary Tree
- LeetCode: Minimum Depth of Binary Tree [111]
- LeetCode 111 Minimum Depth of Binary Tree
- [leetcode 111] Minimum Depth of Binary Tree
- [LeetCode 111]Minimum Depth of Binary Tree
- leetCode #111 Minimum Depth of Binary Tree
- leetcode-111 Minimum Depth of Binary Tree
- leetcode 111 Minimum Depth of Binary Tree
- leetcode || 111、Minimum Depth of Binary Tree
- Leetcode[111]-Minimum Depth of Binary Tree
- leetcode[111]:Minimum Depth of Binary Tree
- LeetCode 111 Minimum Depth of Binary Tree
- [leetcode 111] Minimum Depth of Binary Tree
- leetcode-111-Minimum Depth of Binary Tree
- Leetcode #111 Minimum Depth of Binary Tree
- leetcode 111: Minimum Depth of Binary Tree
- LeetCode 111: Minimum Depth of Binary Tree
- 【LEETCODE】111-Minimum Depth of Binary Tree
- 设计模式---工厂模式
- ANDROID缩略图Thumbnails
- 如何解决Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (gbk_chinese_ci,IMPLICIT)的问题
- 一个好用的查询不同国家时间的网站timeanddate.com
- Android Camera API2.0下全新的Camera FW/HAL架构简述
- LeetCode 111: Minimum Depth of Binary Tree
- diff && patch 命令制作补丁
- iOS行业
- iOS 9 适配系列教程
- Java AbstractCollection源码分析
- ZOJ 1099这道题如果从文件中读取数据,最关键的地方是处理好空格,按时我一直没有成功,所以这道题中没有使用文件
- What's new in Android M - Run Time Permission
- 认识REST
- js的insertRow(-1)和insertCell(-1)