Balanced Binary Tree


/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if (root == null)
return true;
else {
if (!isBalanced(root.left) || !isBalanced(root.right))
return false;
else if (Math.abs(getDepth(root.left) - getDepth(root.right)) <= 1)
return true;
else
return false;
}
}

public int getDepth(TreeNode root){
if (root == null)
return 0;
else
return Math.max(getDepth(root.left), getDepth(root.right)) + 1;
}
}

小测试过了 大测试超时= = 哎。。。递归果然就是时间效率不高
想了一下发现是isBalanced中已经用isBalanced算过一次深度了 之后又算一次深度 囧


/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.HashMap;
public class Solution {
static HashMap<TreeNode, Integer> depths = new HashMap<TreeNode, Integer>();
public boolean isBalanced(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if (root == null)
return true;
else {
if (!isBalanced(root.left) || !isBalanced(root.right))
return false;
else if (Math.abs(getDepth(root.left) - getDepth(root.right)) <= 1)
return true;
else
return false;
}
}

public int getDepth(TreeNode root){
if (root == null)
return 0;
else
if (depths.containsKey(root))
return depths.get(root);
else{
depths.put(root, Math.max(getDepth(root.left), getDepth(root.right)) + 1);
return depths.get(root);
}
}
}


啊 然后写了一个HashMap存了一下深度就好了。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值