Minimum Depth of Binary Tree
来源:互联网 发布:注册淘宝要多少钱 编辑:程序博客网 时间:2024/05/21 08:53
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.
方法一:从根节点开始计数,直到叶子节点,寻找最短路径.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int depthCore(TreeNode *root,int depth){ if (!root->left && !root->right) return depth; int max = (unsigned int)(~0)>>1; int left = max; int right = max; if (root->left) left = depthCore(root->left,depth+1); if (root->right) right = depthCore(root->right,depth+1); return left<right? left:right; } int minDepth(TreeNode *root) { if (!root) return 0; return depthCore(root,1); }};
方法二:
从叶子节点开始计数,直到根节点,寻找最短路径.
/** * Definition for binary tree * 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) return 0; int left = minDepth(root->left); int right = minDepth(root->right); if (left*right!=0) return min(left,right)+1; if (left==0) return right+1; if (right==0) return left+1; }};
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
- 移动开发者必须了解的10大跨平台工具
- iOS项目的目录结构和开发流程
- statusbar
- 几篇关于Amazon AWS的技术文章
- 买不到的数目
- Minimum Depth of Binary Tree
- oracle数据库导入导出命令!
- 昨天开始安装SDK,出现问题一直不能成功,终于解决了
- ubuntu 12.04 命令行不显示用户名和路径了
- C# InitializeComponent()的作用
- Dev C++, 不知道是不是能够流行?
- Mongodb在Windows下安装及配置
- iOS学习之UITableView(一): 新手篇创建tableView
- poj3159