LeetCode110-Balanced Binary Tree

落日映苍穹つ 2022-08-04 12:48 123阅读 0赞

LeetCode 110 : Balanced Binary Tree

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.

问题来源: https://leetcode.com/problems/balanced-binary-tree/

问题的大概意思是给一个二叉树,判断该树是否为平衡二叉树(平衡二叉树的判断条件:左右子树的高度相差最大不超过1)。

解题思路:通过递归找出每一个二叉树的左右子树的高度,然后比较左右子树高度差是否不超过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 boolean isBalanced(TreeNode root) {
  12. if(null==root){
  13. return true;
  14. }
  15. else{
  16. return isBalancedTree(root);
  17. }
  18. }
  19. private boolean isBalancedTree(TreeNode node){
  20. if(null==node){
  21. return true;
  22. }
  23. else{
  24. int leftChildHeight = getHeight(node.left);
  25. int rightChildHeight = getHeight(node.right);
  26. return (Math.abs(leftChildHeight-rightChildHeight)<=1) && isBalancedTree(node.left) && isBalancedTree(node.right);
  27. }
  28. }
  29. private int getHeight(TreeNode node){
  30. if(null==node){
  31. return 0;
  32. }
  33. else{
  34. int leftChildHeight = getHeight(node.left);
  35. int rightChildHeight = getHeight(node.right);
  36. return (leftChildHeight >= rightChildHeight) ? leftChildHeight+1 : rightChildHeight+1;
  37. }
  38. }
  39. }

发表评论

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

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

相关阅读