LeetCode(110):平衡二叉树

Easy!

题目描述:

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

返回 false 。

解题思路:

求二叉树是否平衡,根据题目中的定义,高度平衡二叉树是每一个节点的两个字数的深度差不能超过1,那么我们肯定需要一个求各个点深度的函数,然后对于每个节点的两个子树来进行深度差的比较,时间复杂度为O(NlgN)。

C++解法一:

 1 class Solution {
 2 public:
 3     bool isBalanced(TreeNode *root) {
 4         if (!root) return true;
 5         if (abs(getDepth(root->left) - getDepth(root->right)) > 1) return false;
 6         return isBalanced(root->left) && isBalanced(root->right);    
 7     }
 8     int getDepth(TreeNode *root) {
 9         if (!root) return 0;
10         return 1 + max(getDepth(root->left), getDepth(root->right));
11     }
12 };

上面那个方法正确但不是很高效,因为每一个点都会被上面的点计算深度时访问一次,我们可以进行优化。方法是如果我们发现子树不平衡,则不计算具体的深度,而是直接返回-1。那么优化后的方法为:对于每一个节点,我们通过checkDepth方法递归获得左右子树的深度,如果子树是平衡的,则返回真实的深度,若不平衡,直接返回-1,此方法时间复杂度O(N),空间复杂度O(H)。

C++解法二:

 1 class Solution {
 2 public:    
 3     bool isBalanced(TreeNode *root) {
 4         if (checkDepth(root) == -1) return false;
 5         else return true;
 6     }
 7     int checkDepth(TreeNode *root) {
 8         if (!root) return 0;
 9         int left = checkDepth(root->left);
10         if (left == -1) return -1;
11         int right = checkDepth(root->right);
12         if (right == -1) return -1;
13         int diff = abs(left - right);
14         if (diff > 1) return -1;
15         else return 1 + max(left, right);
16     }
17 };

 

posted @ 2018-06-10 11:02  Ariel_一只猫的旅行  阅读(338)  评论(0编辑  收藏  举报