(015)實現一個函數檢查一棵樹是否平衡(keep it up),015keep
實現一個函數檢查一棵樹是否平衡。對於這個問題而言, 平衡指的是這棵樹任意兩個葉子結點到根結點的距離之差不大於1。
這個題我們可以採用暴力搜尋,找到葉子節點到根節點的最小值和最大值,然後他們的差如果大於1就不是平衡樹,反之
則是平衡樹。
int MinDepth = std::numeric_limits<int>::max();int MaxDepth = std::numeric_limits<int>::min();struct TreeNode{int data;TreeNode* child;TreeNode* brother;};bool isBlanceTree(const TreeNode* vNode, int vDepth=0){if (vNode == NULL){if (vDepth == 0) return true;if (vDepth < MinDepth) {MinDepth = vDepth;}if (vDepth > MaxDepth){MaxDepth = vDepth;}if (MaxDepth - MinDepth > 1) return false;return true;}bool IsBlance = true;if (vNode->child != NULL){IsBlance = isBlanceTree(vNode->child, vDepth+1);}if (IsBlance && vNode->brother != NULL){IsBlance = isBlanceTree(vNode->brother, vDepth);}return IsBlance;}
編寫一個函數,以一棵樹為輸入,返回樹的結點數目
假設你的樹是這樣定義的:
struct tree{
int i;
struct tree *left;
struct tree *right;
};
那麼可以這麼寫:
int fun(struct tree *t){
if(t==0) return 0;
else return 1+fun(t->left)+fun(t->right);
}
=======================================
把你說的樹的結構寫出來。
=======================================
你的定義和我的有什麼區別?不一樣是二叉樹?
3 編寫一個函數,以一棵樹為輸入,返回樹的結點數目就隨便一棵樹,不是二叉樹的C++資料結構解答
以下是二叉樹類型的,如果還要,我可以幫你改。
#include "stdio.h"
#include "conio.h"
typedef struct node
{
struct node *l,*r;
}Node;
int getTreeNum(Node * k)
{
if(k!=0)
return 1+getTreeNum(k->l)+getTreeNum(k->r);
else
return 0;
}
int main()
{
Node *root=(Node*)malloc(sizeof(Node));
root->l=(Node*)malloc(sizeof(Node));
root->r=(Node*)malloc(sizeof(Node));
root->r->l=0;
root->r->r=0;
root->l->r=0;
root->l->l=(Node*)malloc(sizeof(Node));
root->l->l->l=0;
root->l->l->r=0;
printf("%d",getTreeNum(root));
getch();
}