思路:
一开始想着怎么遍历来找,想了一会找不到什么思路,然后突然发现可以用递归来做
递归思路也很简单:返回True的条件=左子树为True+右子树为True+左右子树深度差不超过1
于是写出代码:
class Solution { public boolean isBalanced(TreeNode root) { if(root==null) {return true;}//程序的出口是什么 if(isBalanced(root.left)&&isBalanced(root.right)) { if(Math.abs(height(root.left)-height(root.right))<=1) {return true;} } return false; } public int height(TreeNode root){ if(root==null) {return 0;} return Math.max(height(root.left),height(root.right))+1; } }
然后让我们分析一下这个是什么遍历,然后分析一下复杂度
什么顺序遍历看你的代码怎么写
复杂度的话,我们很清楚的能看到,我们造成了很多重复计算
例如计算root的左右子树高度差时,就需要计算左子树的高度,在计算左子树是否满足要求时也要计算这些,有很多重复运算
那么这个属于从上往下,浪费了很多运算,如果从下往上,是否就可以不重复计算
class Solution { public boolean isBalanced(TreeNode root) { return recur(root) != -1; } private int recur(TreeNode root) { if (root == null) return 0; int left = recur(root.left); if(left == -1) return -1; int right = recur(root.right); if(right == -1) return -1; return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1; } }
具体看这道题的解析
感觉还是有点难想出来