110. Balanced Binary Tree (平衡二叉树判断)

迈不过友情╰ 2022-07-15 01:18 256阅读 0赞

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public int depth(TreeNode root){
  12. if(root==null)
  13. return 0;
  14. return Math.max(depth(root.left),depth(root.right))+1;
  15. }
  16. public boolean isBalanced(TreeNode root) {
  17. if(root==null)
  18. return true;
  19. if(Math.abs(depth(root.left)-depth(root.right))>1)
  20. return false;
  21. return isBalanced(root.left)&&isBalanced(root.right);
  22. }
  23. }

发表评论

表情:
评论列表 (有 0 条评论,256人围观)

还没有评论,来说两句吧...

相关阅读