Leetcode: Balanced Binary Tree

傷城~ 2022-08-07 04:35 278阅读 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)要么为空,要么左右子树的深度差值不超过1;(2)左右两个子树都是一棵平衡二叉树,即子树也都要都满足条件(1)。显然这是一个递归的定义。

C++参考示例代码:

  1. /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
  2. class Solution
  3. {
  4. private:
  5. bool checkBalanced(TreeNode *node, int &depth)
  6. {
  7. if (node == NULL)
  8. {
  9. depth = 0;
  10. return true;
  11. }
  12. int leftDepth, rightDepth;
  13. bool leftBalanced = checkBalanced(node->left, leftDepth);
  14. bool rightBalanced = checkBalanced(node->right, rightDepth);
  15. depth = max(leftDepth, rightDepth) + 1;//求以node为根节点的深度
  16. return leftBalanced && rightBalanced && abs(leftDepth - rightDepth) <= 1;
  17. }
  18. public:
  19. bool isBalanced(TreeNode *root)
  20. {
  21. int depth;
  22. return checkBalanced(root, depth);
  23. }
  24. };

发表评论

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

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

相关阅读