Minimum Depth of Binary Tree 二叉树最小深度
2014-04-17 22:46
351 查看
//运用递归的思想,当节点为空时间,即1 2 V 3 V V V 。当左子树为空时,及左子树在具象图上面根本不存在,此时root的深度等于右子树的深度+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) { 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; } }
//也可以从另一方面想,就是当节点为空时间,判断右子树是否存在,当存在时,此节点深度为正无穷(INT_MAX);若不存在,则此节点深度为0
public class MinimumDepthofBinaryTree { public int minDepth(TreeNode root) { if (root == null) return 0; if (root.left == null && root.right == null) return 1; else { int leftDepth = root.left != null ? minDepth(root.left) : Integer.MAX_VALUE; int rightDepth = root.right != null ? minDepth(root.right) : Integer.MAX_VALUE; return Math.min(leftDepth,rightDepth) + 1; } }}就比如说这样
int minDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root == NULL) { return 0; } else { minD(root); } } int minD(TreeNode *root) { if(root->left == NULL && root->right == NULL) { return 1; } else { if(root->left == NULL) { return minD(root->right) + 1; } else if(root->right == NULL) { return minD(root->left) + 1; } else { int left = minD(root->left); int right = minD(root->right); return (left<right?left:right) + 1; } } } };
相关文章推荐
- Minimum Depth of Binary Tree 二叉树的最小深度
- Minimum Depth of Binary Tree(求二叉树的最小深度)
- lintcode minimum-depth-of-binary-tree 二叉树最小深度
- LeetCode OJ:Minimum Depth of Binary Tree(二叉树的最小深度)
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度 [java]
- LeetCode OJ 之 Minimum Depth of Binary Tree(二叉树的最小深度)
- Minimum Depth of Binary Tree 求二叉树最小高度/深度@LeetCode
- 求二叉树的最小深度 Minimum Depth of Binary Tree
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- [LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)
- LeetCode:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- LeetCode:minimum-depth-of-binary-tree(二叉树最小深度)
- [LeetCode] Minimum Depth of Binary Tree 二叉树最小深度
- Minimum Depth of Binary Tree 二叉树的最小深度
- [LeetCode] Minimum Depth of Binary Tree 二叉树的最小深度
- 【leetcode】Minimum Depth of Binary Tree 二叉树的最小深度 (JAVA)
- LeetCode Minimum Depth of Binary Tree 最小深度二叉树
- Leetcode Minimum Depth of Binary Tree 二叉树最小深度