Minimum Depth of Binary Tree
来源:互联网 发布:mac原唱变伴奏 编辑:程序博客网 时间:2024/05/21 19:27
【题目描述】
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.
【思路】一般这样的题目既可以用递归的方法也可以用非递归迭代的方法做。我是用递归的方法做的,思路基本和Maximum Depth of Binary Tree的类似。
【代码】
递归:
/** * 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; if(!root->left&&!root->right) return 1; if(root->left==NULL) return minDepth(root->right)+1; else if(root->right==NULL) return minDepth(root->left)+1; return min(minDepth(root->right),minDepth(root->left))+1; }};
//参考了soulmachine的思路
//pair是一种模板类型,包含两个数据值,两个数据的类型可以不同,pair<typename1,typename2> a,访问的话用a.first,a.second访问
//make_pair函数,自动生成pair对象
/** * 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 result=INT_MAX; stack<pair<TreeNode*,int>> s; s.push(make_pair(root,1)); while(!s.empty()){ TreeNode* node=s.top().first ; int val=s.top().second ; s.pop(); if(node->left==NULL&&node->right==NULL) result=min(result,val); if(node->left&&result>val) s.push(make_pair(node->left,val+1)); if(node->right&&result>val) s.push(make_pair(node->right,val+1)); } return result; }};
0 0
- 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
- 关于JavaScript中数组去重(任意数据类型)
- 自己-社会-机器学习
- LintCode 乱序字符串
- C++--内建类型所占的字节数与内建类型转换
- 创建视图和副本
- Minimum Depth of Binary Tree
- https 之 ssl 证书
- jsp动态显示时间
- 对于Objective-C新建类的理解
- Android开发工具ADT关联源码与API文档
- Spring中ApplicationContext和beanfactory区别
- 回归问题
- 指针的指针字符串排序
- Java语句——for循环