【leetcode】【easy】110. Balanced Binary Tree

110. 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 left and right subtrees of every node differ in height by no more than 1.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.
Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

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

Return false.

题目链接:https://leetcode-cn.com/problems/balanced-binary-tree/

思路

本来的思路:分别计算最大深度和最小深度,相减差与1比较。

问题:特殊例子[1,null,2,null,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:
    bool isBalanced(TreeNode* root) {
        if (!root) return true;
        if(getDep(root)<0) return false;
        else return true;
    }
    int getDep(TreeNode* root){
        if (!root) return 0;
        int l = getDep(root->left);
        int r = getDep(root->right);
        if(l<0 || r<0 || abs(l-r)>1) return -1;
        else return max(l,r)+1;
    }
};
发布了127 篇原创文章 · 获赞 2 · 访问量 3744

猜你喜欢

转载自blog.csdn.net/lemonade13/article/details/104390872