輸入一棵二叉樹,判斷該二叉樹是不是平衡二叉樹。java
深度搜索,剪枝。
時間複雜度O(lgn),空間複雜度O(lgn)。code
public class Solution { private int depth(TreeNode root) { return root == null ? 0 : Math.max(1+depth(root.left), 1+depth(root.right)); } public boolean IsBalanced_Solution(TreeNode root) { return root == null ? true : Math.abs(depth(root.left) - depth(root.right)) <= 1; } }
public class Solution { private int depth(TreeNode root) { if(root == null) return 0; int left = depth(root.left); if(left == -1){ return -1; } int right = depth(root.right); if(right == -1) { return -1; } return Math.abs(left-right) < 2 ? 1 + Math.max(left, right) : -1; } public boolean IsBalanced_Solution(TreeNode root) { return depth(root) != -1; } }