leetcode之Minimum Depth of Binary Tree
来源:互联网 发布:位面淘宝txt八零 编辑:程序博客网 时间:2024/05/21 16:21
题目大意:
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.
意思就是:
给定一棵二叉树, 球它的最小高度
解体思路:
DFS. 同时定义一个变量作为当前最小值, 每次求的一条路径, 就和改变量做比较, 最后所有的路径都遍历完之后,就可求得最小值.
代码如下:
/** * 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 depth = 0, min = -1;return binTreePreTravel(root, depth, min); }int binTreePreTravel(TreeNode* root, int depth, int& min){depth++;if(root->left){binTreePreTravel(root->left, depth, min);}if(root->right){binTreePreTravel(root->right, depth, min);}if(!root->left && !root->right){if(min != -1){min = (min < depth? min: depth);}else if(min == -1){min = depth;}}return min;}};
0 0
- 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之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
- [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 - BFS
- [LeetCode] Minimum Depth of Binary Tree - DFS
- 高效运算
- android 获得屏幕、视图、任务栏、状态栏的高宽以及屏幕的设置
- SSL握手过程详解
- UVa 12372 - Packing for Holiday
- [leetcode] Longest Consecutive Sequence
- leetcode之Minimum Depth of Binary Tree
- #pragma预处理命令
- poj 1129(图的着色问题)
- 怎么把Android手机的通讯录导入到iphone手机中
- ORA-01855: AM/A.M. or PM/P.M. required问题排查与解析
- DH 密钥交换
- 黑马程序员——Java基础语法(上)
- const的一些浅层谈论
- hd 2000 ASCII码排序