Minimum Depth of Binary Tree--LeetCode
2015-04-05 10:30
218 查看
题目:
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.
思路:这里递归就需要注意一些东西了,对于非递归来说,只要发现有一个节点没有左子树同时也没有右子树,那么这个就是节点所在层次就是目标
int MinDepth(BinTree* root) { if(root == NULL) return 0; if(root->left == NULL) return MinDepth(root->right)+1; if(root->right == NULL) return MinDepth(root->left)+1; return min(MinDepth(root->left),MinDepth(root->right))+1; } int MinDepth_second(BinTree* root) { if(root == NULL) return 0; BinTree* node; deque<BinTree*> de; int num; int curnum=0; int level=0; de.push_back(root); num=1; while(!de.empty()) { node = de.front(); de.pop_front(); num--; if(node->left==NULL && node->right == NULL) return level+1; if(node->left != NULL) { de.push_back(node->left); curnum++; } if(node->right !=NULL) { de.push_back(node->right); curnum++; } if(num == 0) { num = curnum; curnum=0; level++; } } return level; }
相关文章推荐
- [面试真题] LeetCode:Minimum Depth of Binary Tree
- LeetCode:Minimum Depth of Binary Tree
- [leetcode刷题系列]Minimum Depth of Binary Tree
- LeetCode: Minimum Depth of Binary Tree
- 【leetcode】Minimum Depth of Binary Tree
- [Leetcode] Minimum Depth of Binary Tree
- leetcode 31: Minimum Depth of Binary Tree
- leetcode--Minimum Depth of Binary Tree
- [LeetCode] Minimum Depth of Binary Tree - BFS
- LeetCode-Minimum Depth of Binary Tree
- 【LeetCode with Python】 Minimum Depth of Binary Tree
- [leetcode]Minimum Depth of Binary Tree
- Leetcode: Minimum Depth of Binary Tree
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- leetcode: Minimum Depth of Binary Tree
- 【leetcode】Minimum Depth of Binary Tree
- [LeetCode]Minimum Depth of Binary Tree
- LeetCode_Minimum Depth of Binary Tree
- LeetCode题目笔记(一) -- Minimum Depth Of Binary Tree
- leetcode -- Minimum Depth of Binary Tree