Leetcode 110 Balanced Binary Tree

来源:互联网 发布:java井字棋界面设计 编辑:程序博客网 时间:2024/05/01 23:38

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.


平衡二叉树 左右子树height相差不超过1 且均为平衡二叉树

。。。第一次直接accept。。。orz 我还以为系统坏了= =

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isBalanced(TreeNode root) {        if(root == null)        return true;        boolean height = false;        int diff = height(root.right)-height(root.left);        if(diff == 0 || diff == 1 ||diff == -1 )  height = true;        return(isBalanced(root.right)&&isBalanced(root.left)&&height);    }            public int height(TreeNode root){        if(root == null)  return 0;        int result = 0;        result++;       int height_left = height(root.left);       int height_right = height(root.right);       result+= height_left>height_right? height_left:height_right;       return result;            }}

我觉得我的做法还是复杂了。。膜拜一下大神的做法

public boolean isBalanced(TreeNode root) {    if(root==null){        return true;    }    return height(root)!=-1;//这个返回值-1就是代表左右子树height之差    }public int height(TreeNode node){    if(node==null){        return 0;    }    int lH=height(node.left);    if(lH==-1){        return -1;    }    int rH=height(node.right);    if(rH==-1){        return -1;    }    if(lH-rH<-1 || lH-rH>1){        return -1;//如果说当前节点为root的子树不是平衡二叉树 返回值置为-1 也就是说只要有一个不满足就直接gg    }    return Math.max(lH,rH)+1;//满足才计算height}
我就没想到一个不满足就刚刚节约时间这种优化==还是young。。。


0 0
原创粉丝点击