您的位置:首页 > 其它

Minimum Depth of Binary Tree ---LeetCode

2016-11-29 21:32 260 查看
https://leetcode.com/problems/minimum-depth-of-binary-tree/

解题思路:

Maximum Depth of Binary Tree 这道题相反,是求二叉树的最小深度。贴两种写法:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;

if (root.left == null && root.right == null) return 1;

int left  = root.left  != null ? minDepth(root.left)  : Integer.MAX_VALUE;
int right = root.right != null ? minDepth(root.right) : Integer.MAX_VALUE;

return Math.min(left, right) + 1;
}
}


/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;

int left = minDepth(root.left), right = minDepth(root.right);

return 1 + (Math.min(left, right) > 0 ? Math.min(left, right) : Math.max(left, right));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: