leetcode 31: Minimum Depth of Binary Tree
来源:互联网 发布:手机系统优化排行榜 编辑:程序博客网 时间:2024/05/01 05:56
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.
1. different from maximum depth. if a node only has one child, the depth will be 1 + child depth.
public class Solution { public int minDepth(TreeNode 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 Math.min(minDepth(root.right), minDepth(root.left)) + 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) { // Start typing your C/C++ solution below // DO NOT write int main() function return minRec(root); } int minRec( TreeNode * root) { if(!root) return 0; int left = minRec( root->left); int right = minRec( root->right); if(left && right) return 1 + min(left, right); if(left || right) return 1+left+right; return 1; }};
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int minDepth(TreeNode root) { // Start typing your Java solution below // DO NOT write main() function return minRec(root); } private int minRec(TreeNode root) { if(root==null) return 0; int l = minRec(root.left); int r = minRec(root.right); if(l==0) return r+1; if(r==0) return l+1; return Math.min(l, r) + 1; }}
- leetcode 31: 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 - BFS
- [LeetCode] Minimum Depth of Binary Tree - DFS
- 【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
- 核心动画 CoreAnimation
- 新版Safari在Windows 下启动CPU占用100%的问题
- Python
- Makefile: Makefile中的变量数据库和隐含规则
- CodeSmith 使用教程(6): 基本语法-声明和使用属性
- leetcode 31: Minimum Depth of Binary Tree
- 《电子电气工程师必知必会》
- Javascript学习系列(七):Javascript 引用activex控件
- wxPython中frame的style
- c编译过程
- WinCE下数字键盘
- 思路清晰远比卖力苦干重要
- Unicode之痛
- 计算广告学习笔记1.3 广告的基础知识-广告与营销的区别