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.

解题思路:
这道题其实就是应用DFS,对于一颗二叉树边计算树的高度边计算差值,针对树里面的每一个节点计算它的左右子树的高度差,如果差值大于1,那么就返回-1,如果不大于1,从下往上再次检测.

时间复杂度:
由于是运用DFS,所以时间复杂度为O(n).

代码如下:

  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. //corner case check
  14. if(root == NULL)
  15. return true;
  16. int isBalanced = getHeight(root);
  17. if(isBalanced != -1)
  18. return true;
  19. else
  20. return false;
  21. }
  22. int getHeight(TreeNode* root)
  23. {
  24. if(root == NULL)
  25. return 0;
  26. int leftHeight = getHeight(root->left);
  27. if(leftHeight == -1)
  28. return -1;
  29. int rightHeight = getHeight(root->right);
  30. if(rightHeight == -1)
  31. return -1;
  32. int diffHeight = rightHeight > leftHeight? rightHeight-leftHeight:leftHeight-rightHeight;
  33. if(diffHeight > 1)
  34. return -1;
  35. else
  36. return diffHeight = (rightHeight>leftHeight?rightHeight:leftHeight)+1;
  37. }
  38. };