判断是否为平衡二叉树--递归法
2016-03-13 21:19
281 查看
求树的深度
用递归做很简单,只要知道递归出口语句的别写错。[cpp] view
plaincopy
struct BinaryTreeNode
{
int m_Value;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
int TreeDepth(BinaryTreeNode* pRoot)
{
if (pRoot == NULL)
return 0;
int nLeftDepth = TreeDepth(pRoot->m_pLeft);
int nRightDepth = TreeDepth(pRoot->m_pRight);
return (nLeftDepth>nRightDepth)?(nLeftDepth+1):(nRightDepth+1);
}
判断该树是否为平衡二叉树
调用上述函数求每个节点的左右孩子深度[cpp] view
plaincopy
bool IsBalanced(BinaryTreeNode* pRoot)
{
if(pRoot== NULL)
return true;
int nLeftDepth = TreeDepth(pRoot->m_pLeft);
int nRightDepth = TreeDepth(pRoot->m_pRight);
int diff = nRightDepth-nLeftDepth;
if (diff>1 || diff<-1)
return false;
return IsBalanced(pRoot->m_pLeft)&&IsBalanced(pRoot->m_pRight);
}
相关文章推荐
- 这段代码在32位计算机上的执行结果是什么?
- HTTP请求和数据安全
- HDU 2187
- 关系模型之关系代数
- mapreduce的shuffle阶段详解
- HDU 1423 —— Greatest Common Increasing Subsequence
- iOS开发UI篇—核心动画(基础动画)
- 从AlphaGO的胜利来看人类趋势
- Python设计模式(3)-工厂方法模式
- C++11 半同步半异步线程池的实现
- css基本语法
- 记录
- 写一个语句实现x是否为2的若干次幂的判断
- 使用dex2jar反编译apk
- 交换两个数的值,不引用第三个变量
- 指针与数组的区别详解
- 1064. Complete Binary Search Tree (30)
- XML的解析方式
- 如何用命令将Farm Solution部署到SharePoint?
- 哈夫曼算法解压文件前两步