LeetCode110.Balanced Binary Tree题解

1. 题目描述

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.

2. 分析

根据平衡二叉树(BST)的定义:给出一棵树的根节点,让我们判断这棵树是不是满足平衡二叉树的条件:即任意一个节点的左右子树的深度之差不大于1.
拿到题目,我的第一反应就是先设计一个求树的深度的函数,然后再对整棵树进行递归遍历,判断每个节点下面的左右子树深度之差,如果大于1的话,则为false。用了9ms过了226个测试样例,如下:
这里写图片描述

3. 源码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int getDepth(TreeNode* root) {
        if (root == NULL) {
            return 0;
        }
        int leftDepth = getDepth(root->left);
        int rightDepth = getDepth(root->right);
        if (leftDepth > rightDepth) {
            return leftDepth+1;
        }
        return rightDepth+1;
    }
    bool isBalanced(TreeNode* root) {
        if (root == NULL) {
            return true;
        }
        int leftDepth = getDepth(root->left);
        int rightDepth = getDepth(root->right);
        if (abs(leftDepth - rightDepth) <= 1) {
           if(isBalanced(root->left) == true && isBalanced(root->right) == true) {
               return true;
            }
            return false;
        }
        return false;
    }
};

4. 心得

这是BST比较基础的题目,但是在做的时候还是交了3次才得到正确结果。2次失败的原因是:

4.1. 第1次失败

没有通过样例[1,2,2,3,null,null,3,4,null,null,4],这是因为我只考虑了根节点左右子树深度之差满足条件,而忘记了每一个节点都需要。

4.2. 第2次失败

没有通过样例[1,2,3,4,5,null,6,7,null,null,null,null,8],这是因为在设计返回值条件的时候只遍历了左子树,没有遍历右子树的情况。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章