#155 Minimum Depth of Binary Tree
来源:互联网 发布:python web 开发 编辑:程序博客网 时间:2024/04/30 15:23
题目描述:
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.
Example
题目思路:Given a binary tree as follow:
1 / \ 2 3 / \ 4 5
The minimum depth is 2
.
这题我还是用了bfs比较方便,用一个queue来记录从top到bottom的nodes,再用一个queue来记录相应nodes的level。当发现有node没有子树的时候,它的level就是我们所在的答案。
Mycode(AC = 76ms):
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /** * @param root: The root of binary tree. * @return: An integer */ int minDepth(TreeNode *root) { // write your code here if (root == NULL) { return 0; } // store the nodes from top to bottom queue<TreeNode *> helper; helper.push(root); // store the level of each node queue<int> levels; levels.push(1); int level; while (!helper.empty()) { // get the node and level from front of queue TreeNode *node = helper.front(); helper.pop(); level = levels.front(); levels.pop(); // if it is single node, then return level if (!node->left && !node->right) { return level; } // push the left/right node into queue if (node->left) { helper.push(node->left); levels.push(level + 1); } if (node->right) { helper.push(node->right); levels.push(level + 1); } } return level; }};
0 0
- #155 Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- 快排
- comparator接口与Comparable接口的区别
- 网格
- Java概述
- 凸包
- #155 Minimum Depth of Binary Tree
- 使用光线投射实现相机跟随
- web前端面试题
- jquery判断子元素是否存在
- 快捷方式
- ios托管网站
- Proxies for Shortest Path and Distance Queries
- 计算器的改良 (模拟)
- Android 自定义View 环绕六边形控件及其TouchEvent事件的监听