面试题09 从二叉树的深度扩展到判断是否是二叉平衡树 【树】 Dserving thinking
2013-01-21 20:32
477 查看
判断二叉树是否是平衡二叉树,二叉树深度
#include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <cstdio> #include <cmath> #include <vector> #include <stack> #include <deque> #include <queue> #include <bitset> #include <list> #include <map> #include <set> #include <iterator> #include <algorithm> #include <functional> #include <utility> #include <sstream> #include <climits> #include <cassert> #define BUG puts("here!!!"); using namespace std; struct Node { int value; Node *lchild, *rchild; }; int treeDep(Node* root) { if(root == NULL) return 0; int nLeft = treeDep(root->lchild); int nRight = treeDep(root->rchild); return (nLeft > nRight ? nLeft : nRight) + 1; } bool isBalance(Node* root) { if(root == NULL) return true; int left, right; left = treeDep(root->lchild); right = treeDep(root->rchild); int diff = left - right; if(diff < -1 || diff > 1) { return false; } return isBalance(root->lchild) && isBalance(root->rchild); } bool isBalance(Node* root, int *dep) { // 地址传递 if(root == NULL) { *dep = 0; return true; } else { int left, right; if(isBalance(root->lchild, &left) && isBalance(root->rchild, &right)) { int diff = left - right; if(diff >= -1 || diff <= 1) { *dep = (left > right ? left : right) + 1; return true; } } return false; } } int main() { return 0; }
相关文章推荐
- 面试题09 从二叉树的深度扩展到判断是否是二叉平衡树 【树】 Dserving thinking
- 剑指offer 面试题39 求二叉树深度|判断是否为平衡二叉树
- 求二叉树的深度及判断一个二叉树是否是二叉平衡树(剑指offer39)
- 【面试题】剑指Offer-39-求二叉树的深度和判断一颗树是否为平衡二叉树
- 面试题39:获得二叉树深度和判断是否是平衡二叉树
- 数据结构面试题/判断一棵二叉树是否是平衡二叉树
- 剑指Offer_面试题39_二叉树的深度 & 判断平衡二叉树
- 剑指offer——面试题39:扩展问题判断一个树是否是平衡二叉树(递归)
- 二叉树的深度,判断是否是平衡二叉树
- 【面试题】判断一棵二叉树是否是完全二叉树
- 二叉树面试题之判断一棵树是否为另一棵树的子树
- 求二叉树深度、判断是否是平衡二叉树
- 三:求二叉树的深度以及判断二叉树是否平衡
- 【IT笔试面试题整理】判断一个二叉树是否是平衡的?
- 判断任一二叉树,是否为满二叉树.(输出二叉树,节点总数,二叉树深度)
- 39 二叉树的深度和宽度以及判断是否是平衡二叉树
- 二叉树的深度求值和判断是否是平衡
- 剑指offer面试题39:二叉树深度以及判断平衡二叉树
- 二叉树的深度以及判断二叉树是否为平衡二叉树
- 【面试题】剑指offer18--判断一个二叉树是否为另一个二叉树的子结构