class Solution: def isBalanced(self, root: TreeNode) -> bool: if not root: return True def helper(node): if not node: return 0 left=helper(node.left) right=helper(node.right) return max(left,right)+1 return abs(helper(root.left)-helper(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)
执行用时 :76 ms, 在所有 python3 提交中击败了60.84%的用户
内存消耗 :19.6 MB, 在所有 python3 提交中击败了5.15%的用户
——2019.11.15
简单题还是可以掌握的,逻辑也简单
public boolean isBalanced(TreeNode root) { if(root == null){ return true; } return Math.abs(height(root.left) - height(root.right))<2 && isBalanced(root.left) && isBalanced(root.right); } //如何获取一棵树的高度 private int height(TreeNode root) { if(root == null){ return 0; }else{ return Math.max(height(root.left),height(root.right))+1; } }
——2020.7.1