Lintcode 93. 平衡二叉树
题目链接:https://www.lintcode.com/problem/balanced-binary-tree/description
描述:给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
代码实现主要用了遍历的方法进行递归。此外,在实现的过程中使用了C++中的pair类型作为函数的返回类型,这样可以一次返回两个数据。关于pair的基础知识可以参考这篇博文:C++ pair的基本用法总结(整理)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
typedef pair<bool, int> Result;
//递归的定义
Result isBalancedSubtree(TreeNode * root) {
Result res(true, 0), left, right;
//递归的出口
if (NULL == root) {
return res;
}
//递归的拆解
left = isBalancedSubtree(root->left);
right = isBalancedSubtree(root->right);
res.second = (left.second > right.second ? left.second : right.second) + 1;
if (abs(left.second - right.second) <= 1 && left.first && right.first) {
res.first = true;
} else {
res.first = false;
}
return res;
}
bool isBalanced(TreeNode * root) {
Result res;
//递归的调用
res = isBalancedSubtree(root);
return res.first;
}
};