码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 110

时间:2016-07-06 20:14:55      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

打了两年多的ACM竞赛,没留下写题解的习惯,趁着毕业之后的暑假为了去美帝找实习做准备,刷点题

先从LeetCode的简单题刷起,练练手,慢慢找回感觉

LeetCode110: 判断一棵二叉树树是否是平衡树

由于之前遇到数据结构的都直接扔给队友,最基本的都没怎么做过,遇到的数据结构基本都是新知识点,记下来

二叉平衡树定义为:binary tree in which the depth of the two subtrees of every node never differ by more than 1.

即任意一个节点的两个子树深度差不超过1.

先写一个函数递归得到任意一个节点的深度,

判断是否为平衡树的条件为:

1.根节点为空,是

2.根节点不为空,左右两子树的深度差1以上,不是

3.左右两子树的深度差1以内,如果两个子树都是平衡树,则是,否则不是

代码:(代码为leetcode中c++的格式)

/**
* 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 dept(TreeNode *root){    //返回子树深度
if(root == NULL)
return 0;
if(root -> left == NULL && root ->right == NULL)
return 1;
return max(dept(root->left),dept(root->right)) + 1;
}

bool isBalanced(TreeNode* root) {  //递归判断是否为平衡树
if(root == NULL)
return true;
int x = dept(root->left) - dept(root->right);
if(x > 1 || x < -1)
return false;
else
return isBalanced(root->left) && isBalanced(root->right);
}
};

LeetCode 110

标签:

原文地址:http://www.cnblogs.com/nevgivin/p/5647950.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!