【LeetCode】111. Minimum Depth of Binary Tree
2016-10-06 14:55
330 查看
题目:
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.
分析:
这道题的要求是求一颗二叉树的最小高度,即从根节点到叶子结点所经过的结点数目。我的想法是使用BFS来求解这个问题。
设3个变量depth,cur,next来分别记录二叉树的高度,当前层没遍历过的结点数,下一层没遍历的结点数。每遍历一层,depth就加1.当遍历到叶子结点时,返回depth。这个算法的复杂度为O(N).
代码:
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.
分析:
这道题的要求是求一颗二叉树的最小高度,即从根节点到叶子结点所经过的结点数目。我的想法是使用BFS来求解这个问题。
设3个变量depth,cur,next来分别记录二叉树的高度,当前层没遍历过的结点数,下一层没遍历的结点数。每遍历一层,depth就加1.当遍历到叶子结点时,返回depth。这个算法的复杂度为O(N).
代码:
/** * 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 depth = 0,cur = 0,next = 0; queue<TreeNode*> q; q.push(root); depth++; cur++; while(!q.empty()) { TreeNode* temp =q.front(); q.pop(); cur--; if(temp->left == NULL&&temp->right ==NULL) return depth; if(temp->left!=NULL) { q.push(temp->left); next++; } if(temp->right != NULL) { q.push(temp->right); next++; } if(cur == 0) { depth++; cur = next; next = 0; } } return depth; } };
相关文章推荐
- LEETCODE —— Binary Tree的3 题 —— 3种非Recursive遍历
- Leetcode 111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- [LeetCode] 543. Diameter of Binary Tree
- [LeetCode]--104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- LeetCode 105,106. Construct Binary Tree 重建二叉树 Python Solution
- Leetcode-111. Minimum Depth of Binary Tree
- [leetcode: Python]543. Diameter of Binary Tree
- leetcode 111. Minimum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- leetcode:104. Maximum Depth of Binary Tree
- [leetcode]: 111. Minimum Depth of Binary Tree
- 【LeetCode】111. Minimum Depth of Binary Tree (2 solutions)
- 【LeetCode】111. Minimum Depth of Binary Tree
- leetcode 每日一题 111. Minimum Depth of Binary Tree
- Leetcode Everyday: 104. Maximum Depth of Binary Tree
- <LeetCode OJ> Invert Binary Tree【226】
- leetcode解题报告:104. Maximum Depth of Binary Tree