一、题目内容

image.png

二、题解

解法1:

思路

左子树深度与右子树深度绝对值小于等于1,同时左右子树都为平衡树,dfs

代码

  1. public class Solution {
  2. public boolean IsBalanced_Solution(TreeNode root) {
  3. if(root == null){
  4. return true;
  5. }
  6. int leftDepth = depth(root.left);
  7. int rightDepth = depth(root.right);
  8. return IsBalanced_Solution(root.left) &&
  9. IsBalanced_Solution(root.right) &&
  10. Math.abs(leftDepth - rightDepth) <= 1;
  11. }
  12. private int depth(TreeNode root){
  13. if(root == null){
  14. return 0;
  15. }
  16. return Math.max(depth(root.left), depth(root.right)) + 1;
  17. }
  18. }