[Leetcode 104, Easy] Minimum (Maximum) Depth of Binary Tree
2013-11-07 05:50
429 查看
Problem:
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.
Analysis:
第一种方法是迭代法。在此不熬述了。
第二种是后序遍历。方法在此也不重复了。只需要说明的是:计算path的长度只能用后续遍历。前序和中序都会在右节点不空时,先弹出根节点,这样计算的path长度就会少一。
Solution:
C++:
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.
Analysis:
第一种方法是迭代法。在此不熬述了。
第二种是后序遍历。方法在此也不重复了。只需要说明的是:计算path的长度只能用后续遍历。前序和中序都会在右节点不空时,先弹出根节点,这样计算的path长度就会少一。
Solution:
C++:
void getDepth(TreeNode *root, vector<TreeNode *> &curPath, vector<vector<TreeNode *> > &Path){ if(root->left==NULL && root->right==NULL){ curPath.push_back(root); Path.push_back(curPath); curPath.erase(curPath.end()-1, curPath.end()); }else{ curPath.push_back(root); if(root->left!=NULL) getDepth(root->left, curPath, Path); if(root->right!=NULL) getDepth(root->right, curPath, Path); curPath.erase(curPath.end()-1, curPath.end()); } } int minDepth(TreeNode *root) { vector<vector<TreeNode *> > Path; if(root==NULL) return 0; vector<TreeNode *> curPath(1, root); if(root->left==NULL && root->right==NULL) return 1; if(root->left!=NULL) getDepth(root->left, curPath, Path); if(root->right!=NULL) getDepth(root->right, curPath, Path); <strong>int minLen=Path[0].size(); for(int i=1; i<Path.size(); ++i){ if(minLen>Path[i].size()) minLen=Path[i].size(); } return minLen;</strong> }
相关文章推荐
- 【leetcode_easy】104-MaximumDepthofBinaryTree
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- <LeetCode OJ> (104 / 111) Maximum & Minimum Depth of Binary Tree
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- [LeetCode#104, 111]Maximum Depth of Binary Tree, Minimum Depth of Binary Tree
- LeetCode #104 - Maximum Depth of Binary Tree - Easy
- 【LeetCode】(104)Maximum Depth of Binary Tree(Easy)
- 【Leetcode-easy-104】Maximum Depth of Binary Tree
- leetcode 104_MaximumDepthOfBinaryTree_easy.py
- Leetcode 104 Maximum Depth of Binary Tree
- leetcode 104 —— Maximum Depth of Binary Tree
- LeetCode 104: Maximum Depth of Binary Tree
- 【Leetcode-easy-111】Minimum Depth of Binary Tree
- LeetCode 104: Maximum Depth of Binary Tree
- LeetCode 104 Maximum Depth of Binary Tree
- Leetcode_104_Maximum Depth of Binary Tree
- LeetCode 104:Maximum Depth of Binary Tree
- LeetCode104 Maximum Depth of Binary Tree
- [LeetCode]: 104: Maximum Depth of Binary Tree
- #111 Minimum Depth of Binary Tree & #104 Maximum Depth of Binary Tree