110. Balanced Binary Tree


1 題目

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.


2 思路

遞歸求解左右子節點的深度,比較深度差,如果深度差大於1,則標記爲不是標準平衡樹。


3 代碼

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    boolean is = true;

	public boolean isBalanced(TreeNode root) {
		treeDeep(root);
		return is;
	}

	public int treeDeep(TreeNode root) {
		if (is) {
			if (root == null) {
				return -1;
			}
			if (root.left == null && root.right == null) {
				return 0;
			}
			int a = 1 + treeDeep(root.left);
			int b = 1 + treeDeep(root.right);

			int abs = Math.abs(a - b);
			if (abs > 1) {
				is = false;
			}
			return Math.max(a, b);
		}
		return 0;
	}
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章