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.
Subscribe to see which companies asked this question
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isBalanced(TreeNode root) { 12 return height(root) != -1; 13 } 14 15 public int height(TreeNode t){ 16 if(t == null) return 0; //到叶子节点再往下的情况 17 int lheight = height(t.left); 18 int rheight = height(t.right); 19 if(lheight == -1 || rheight == -1 || Math.abs(lheight-rheight) > 1){ 20 return -1;//使用-1 标记左右子树高度相差大于1的情况 21 } 22 return 1 + Math.max(lheight,rheight); 23 } 24 }
时间: 2024-12-09 22:09:48