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.

/**

 * 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) {

       

    }

}


给你一个二叉树,判断其是否是高度平衡的。

高度平衡的定义是:每个节点的子树的深度的差值不超过1.


思路:

深度遍历每一个节点,并记录其深度。如果有深度差值超过1的。则不是高度平衡二叉树。

可以设定2个变量,max和min。每当遇到叶子节点的时候,和2个变量比较并更新。

最后根据max-min的值来判断。


初始一个错误解法:

 int max=0;int min=0;
 public boolean isBalanced(TreeNode root) {
  if(root==null) return true;
  dfs(root,0);
  if(max-min>1) return false;
  else return true;
 }
 //参数depth代表调用者的深度。
 public void dfs(TreeNode node,int depth){
  if (node==null) return;
  depth++;
  if(node.left==null&&node.right==null){
   if(min==0) min=depth;
   if(max<depth) max=depth;
   if(min>depth) min=depth;
  }
        dfs(node.left,depth);
        dfs(node.right,depth);
 }



因为没有考虑,只有一个叶子的时候,那max-min=0

用例给的是

1

   |

        2

            |   

                3


说明理解错了题意。对根节点来说,左子树(没有) 右子树深度2.所以不是高度平衡的。


重新编辑算法。

还是深度遍历,但是每次dfs,应该返回子树的深度,并对左右子树的深度作减法。如果大于2 ,则不是高度平衡。

dfs 应该返回以node节点为根的子树深度。并且dfs内部,应该每次判断左子树右子树深度差值的绝对值。

 boolean result=true;
 public boolean isBalanced(TreeNode root) {
  if(root==null) return true;
  dfs(root,0);
  return result;
 }
 //参数depth代表调用者的深度。返回的是左右子节点的深度差
 public int dfs(TreeNode node,int depth){
  if (node==null) return depth;
  depth++;
  if(node.left==null&&node.right==null){
   return depth;
  }
  if (Math.abs(dfs(node.left,depth)-dfs(node.right,depth))>1){
   result=false;
  }
  int left=dfs(node.left,depth);
  int right=dfs(node.right,depth);
  return left>right?left:right;
     
       
 }



算法应该没问题,但是就是后来超时了,明天在解决!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值