您的位置:首页 > 其它

leetcode - Balanced Binary Tree

2014-06-18 21:36 330 查看
题目: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 depth of the two subtrees of every node never differ by more than 1.

个人思路:

1、判断每个节点(子树)的高度差,高度差在绝对值为1的范围内便是平衡二叉树

2、可以适当改造计算树高度的方法,即树的高度为左子树与右子树高度较大者加1

代码:

#include <stddef.h>
#include <iostream>
/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution
{
public:
bool isBalanced(TreeNode *root)
{
balanced = true;
getDepth(root);

return balanced;
}
int getDepth(TreeNode *root)
{
if (root == NULL)
{
return 0;
}

int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);

if (leftDepth - rightDepth > 1 || leftDepth - rightDepth < -1)
{
balanced = false;
}

return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
private:
bool balanced;
};

int main()
{
TreeNode *root = new TreeNode(1);
root->right = new TreeNode(1);
root->right->right = new TreeNode(1);
Solution s;
s.isBalanced(root);
std::cout << root->val << std::endl << root->right->val << std::endl << root->right->val << std::endl;
system("pause");

return 0;
}


View Code

上网搜了一些帖子,方法都是类似,就不贴出来了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: