当前位置:   article > 正文

leetcode 平衡二叉树判断_判断二叉树的平衡性swust oj

判断二叉树的平衡性swust oj

问题描述:

https://oj.leetcode.com/problems/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.

示例代码:

  1. /**
  2. * Definition for binary tree
  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. {
  14. if (!root) return true;
  15. int lh = height(root->left);
  16. int rh = height(root->right);
  17. int diff = lh > rh ? lh - rh : rh - lh;
  18. if (diff > 1) return false;
  19. return isBalanced(root->left) && isBalanced(root->right);
  20. }
  21. int height(TreeNode *root)
  22. {
  23. if (!root) return 0;
  24. int lh = height(root->left);
  25. int rh = height(root->right);
  26. return lh > rh ? lh + 1 : rh + 1;
  27. }
  28. };
该题有可以优化的地方:做了不必要的递归,计算高度和左右子树的判定能否合并??



声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号