LintCode 93: Balanced Binary Tree

93 · Balanced Binary Tree
Algorithms
Easy
Accepted Rate
44%
Description
Solution
Notes
Discuss
Leaderboard
Record

Description
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.

Wechat reply 【Google】 get the latest requent Interview questions. (wechat id : jiuzhang0607)

Example
Example 1:

Input:

tree = {1,2,3}
Output:

true
Explanation:

This is a balanced binary tree.
1
/ \
2 3
Example 2:

Input:

tree = {1,#,2,3,4}
Output:

false
Explanation:

This is not a balanced tree.
The height of node 1’s right sub-tree is 2 but left sub-tree is 0.
1
\
2
/ \
3 4
Tags
Related Problems

95
Validate Binary Search Tree
Medium

467
Complete Binary Tree
Easy

解法1:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

struct RetType {
    int height;
    bool balanced;
    RetType(int h = 0, bool b = true) : height(h), balanced(b) {}
};

class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
    bool isBalanced(TreeNode *root) {
        RetType res = helper(root);
        return res.balanced;
    }
private:
    RetType helper(TreeNode *root) {
        
        if (!root) return RetType(0, true);
        if (!root->left && !root->right) return RetType(1, true);
        RetType leftRet = helper(root->left);
        if (!leftRet.balanced) return RetType(0, false);
        RetType rightRet = helper(root->right);
        if (!rightRet.balanced) return RetType(0, false);
        if (abs(leftRet.height - rightRet.height) > 1) {
            return RetType(0, false);
        } else {
            return RetType(max(leftRet.height, rightRet.height) + 1, true);
        }
    }
};

二刷:用后序遍历。如果递归函数里面又用到其它递归函数,那么时间复杂度很高,可以考虑后序遍历。

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        depth(root);
        return balanced;
    }
private:
    bool balanced = true;
    int depth(TreeNode *root) {
        if (!balanced || !root) return 0; //如果已经!isBalanced,也没有必要继续了。
        int left = depth(root->left);
        int right = depth(root->right);
        if (abs(left - right) > 1) balanced = false;
        return max(left, right) + 1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值