码迷,mamicode.com
首页 > 编程语言 > 详细

[Leetcode][JAVA] Minimum Depth of Binary Tree && Balanced Binary Tree

时间:2015-04-08 07:55:25      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

Minimum Depth of Binary Tree

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。

 需要注意的是如果没有左子树或右子树。那么无条件取存在的那一边子树深度,并+1.

如果左子树和右子树都没有,那么就是叶子节点,返回深度1.

如果root自身为null,返回0

 1 public int minDepth(TreeNode root) {
 2         if(root==null)
 3             return 0;
 4         if(root.left==null && root.right==null)
 5             return 1;
 6         if(root.right==null)
 7             return minDepth(root.left)+1;
 8         if(root.left==null)
 9             return minDepth(root.right)+1;
10         return Math.min(minDepth(root.right),minDepth(root.left))+1;
11     }

 

Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

新定义一个函数,表示树的高度,如果是平衡树的话。不是平衡树则置高度为-1. 运用分治法递归,最后得到结果为-1则不是平衡的。基本情况,root==null则高度为0

 1     public boolean isBalanced(TreeNode root) {
 2         if(height(root)==-1)
 3             return false;
 4         return true;
 5     }
 6     public int height(TreeNode root)
 7     {
 8         if(root==null)
 9             return 0;
10         int left = height(root.left);
11         int right = height(root.right);
12         if(left==-1 || right==-1)
13             return -1;
14         if(Math.abs(left-right)>1)
15             return -1;
16         return Math.max(left,right)+1;
17     }

 

[Leetcode][JAVA] Minimum Depth of Binary Tree && Balanced Binary Tree

标签:

原文地址:http://www.cnblogs.com/splash/p/4401297.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!