110. Balanced Binary Tree

系统管理员 2022-03-26 08:59 310阅读 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.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

  1. 1
  2. / \
  3. 2 2
  4. / \
  5. 3 3
  6. / \
  7. 4 4

Return false.

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. bool isBalanced(TreeNode* root) {
  13. if(root == NULL)
  14. return true;
  15. int lLen = GetLength(root->left);
  16. int rLen = GetLength(root->right);
  17. if(abs(lLen-rLen)>1)
  18. return false;
  19. return isBalanced(root->left) && isBalanced(root->right);
  20. }
  21. private:
  22. int GetLength(TreeNode* root)
  23. {
  24. if(root == NULL)
  25. return 0;
  26. int lLen = GetLength(root->left);
  27. int rLen = GetLength(root->right);
  28. int maxLen = lLen>rLen?lLen:rLen;
  29. return maxLen + 1;
  30. }
  31. };

发表评论

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

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

相关阅读