1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
public class Solution { public boolean IsBalanced_Solution(TreeNode root) { return getDepth(root) != -1; } //用-1表示非平衡二叉树,只要发现,就停止迭代。 private int getDepth(TreeNode root) { if (root == null) { return 0; } int left = getDepth(root.left); if (left == -1) { return -1; } int right = getDepth(root.right); if (right == -1) { return -1; } return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left, right); } }
|
近期评论