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 ofeverynode never differ by more than 1.
Subscribeto see which companies asked this question
Show Tags Show Similar Problems Have you met this question in a real interview? Yes No判斷一棵樹是否是平衡二叉樹。BST的遞歸定義:當一棵樹的左右兩棵子樹的高度只差不超過1,那麼該樹是平衡二叉樹。
用後根遍歷求解。先計算兩棵子樹的高度差。
我的AC代碼
public class BalancedBinaryTree { static boolean ok = true; public static void main(String[] args) { TreeNode n1 = new TreeNode(1); TreeNode n2 = new TreeNode(2); n1.left = n2; System.out.println(isBalanced(n1)); } public static boolean isBalanced(TreeNode root) { ok = true; dfs(root); return ok; } public static int dfs(TreeNode root) { if(root == null || !ok) return 0; int ha = dfs(root.left); int hb = dfs(root.right); if(Math.abs(ha - hb) > 1) ok = false; return Math.max(ha, hb) + 1; } }