您的位置:首页 > 职场人生

面试题09 从二叉树的深度扩展到判断是否是二叉平衡树 【树】 Dserving thinking

2013-01-21 20:32 357 查看
判断二叉树是否是平衡二叉树,二叉树深度
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐