[leedcode 110] 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 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) { //需要构造一个函数求一个节点的高度,然后isBalanced函数每一层开始验证左右字子树是否满足要求,此种思想非常直观 //这种解法效率不高,因为求每个节点是否满足时,需要求一遍高度再验证,然后再求下一层,中间计算有重复计算 //另一种优化算法,在求高度时,就能把信息直接返回,不满足的默认直接回-1,不需要再比较 if(root==null) return true; int left=getDepth(root.left); int right=getDepth(root.right); if(left>right+1||right>left+1) return false; else{ return isBalanced(root.left)&&isBalanced(root.right); } } int getDepth(TreeNode root){ if(root==null) return 0; return Math.max(getDepth(root.left),getDepth(root.right))+1; } /* public boolean isBalanced(TreeNode root){ int temp=getDepth(root); return temp>-1; } public int getDepth(TreeNode root){ if(root==null) return 0; int left=getDepth(root.left); int right=getDepth(root.right); int temp=Math.abs(left-right); if(left==-1||right==-1||temp>1) return -1; return left>right?left+1:right+1; }*/ }