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.
这道题跟之前一道是一样的 就是找binary tree的深度,用分治法解题。但是要返回的是Boolean值 所以就写一个helper程序 在树平衡时候返回深度 不平衡就返回-1 . 然后用Boolean判定最后返回是否为-1
算法的时间是一次树的遍历O(n),空间是栈高度O(logn)。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isBalanced(TreeNode root) { return checkBalance(root) != -1; } public int checkBalance(TreeNode root){ if (root == null){ return 0; } int left = checkBalance(root.left); int right = checkBalance(root.right); if (left == -1|| right == -1|| Math.abs(left - right) > 1){ return -1; }//如果left或者right不平衡就网上返回-1; return Math.max(left, right) + 1; } }
没有评论:
发表评论