(015)實現一個函數檢查一棵樹是否平衡(keep it up),015keep

來源:互聯網
上載者:User

(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();
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.