本文目錄一覽:
- 1、C語言二叉樹求其深度
- 2、C語言二叉樹求最大值求指點?
- 3、C語言 這個求二叉樹深度的函數的思路是什麼 麻煩詳細一點
- 4、哪位大俠知道 求二叉樹深度的類C語言演算法? 謝謝
- 5、C語言中,二叉樹的深度指?怎樣計算
- 6、C語言二叉樹的深度指什麼?怎麼求?
C語言二叉樹求其深度
建議樓主到這裡看看,其實每一層都是有一個return函數,不知道樓主注意到了沒有,其次,reutrn函數初始返回0, 接著有 return (mn?m:n)+1;也就是一個一個一層一層加上去,所以會返回,而最後返回的就是答案
C語言二叉樹求最大值求指點?
問題出在max這個變數上。臨時變數么有返回。可以將這個函數
int getmax(btnode*t,int max)
{
if(t!=NULL)
{
if(maxt-data)
max=t-data;
getmax(t-lchild,max);
getmax(t-rchild,max);
}
return max;
}
修改為:
int getmax(btnode *t, int* max)
{
if(t != NULL)
{
if(*max t-data)
*max = t-data;
getmax(t-lchild, max);
getmax(t-rchild, max);
}
return *max;
}
另外,你要注意你的編碼格式了。需要按照一定的格式來編寫,這樣可以讓別人看的時候更清晰。
C語言 這個求二叉樹深度的函數的思路是什麼 麻煩詳細一點
這是遞歸函數
很容易理解的
二叉樹深度就是左右子樹深度的最大者+1
可見圖片的代碼是錯的
最後的if語句if(depleft)
應該改為if(depleftdepright)
才對
哪位大俠知道 求二叉樹深度的類C語言演算法? 謝謝
主方法調用RootFirst(root,0);即可,g_nMax
即為最終的樹的深度。
int
g_nMax
=
0;
voild
RootFirst(TreeNode
*p,int
nLevel)
{
if
(null
==
p-left
null
==
p-right)
//當前為葉子節點
{
if
(g_nMax
nLevel)
{
g_nMax
=
nLevel;
return;
}
}
if(null
!=
p-left
)
{
RootFirst(p-left,nLevel+1);//遍歷左子樹
}
if(null
!=
p-right)
{
RootFirst(p-right,nLevel+1);//遍歷右子樹
}
}
C語言中,二叉樹的深度指?怎樣計算
二叉樹中結點的最大層數稱為二叉樹的深度。計算:就是結點最大層數的個數,這還用計算,一看就知道。
C語言二叉樹的深度指什麼?怎麼求?
從根節點到葉子結點一次經過的結點形成樹的一條路徑,最長路徑的長度為樹的深度。根節點的深度為1。
解體思路:
1.如果根節點為空,則深度為0,返回0,遞歸的出口。
2.如果根節點不為空,那麼深度至少為1,然後我們求他們左右子樹的深度,
3.比較左右子樹深度值,返回較大的那一個
4.通過遞歸調用
#includeiostream
#includestdlib.h
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
//創建二叉樹結點
BinaryTreeNode* CreateBinaryTreeNode(int value)
{
BinaryTreeNode* pNode=new BinaryTreeNode();
pNode-m_nValue=value;
pNode-m_pLeft=NULL;
pNode-m_pRight=NULL;
return pNode;
}
//連接二叉樹結點
void ConnectTreeNodes(BinaryTreeNode* pParent,BinaryTreeNode* pLeft,BinaryTreeNode* pRight)
{
if(pParent!=NULL)
{
pParent-m_pLeft=pLeft;
pParent-m_pRight=pRight;
}
}
//求二叉樹深度
int TreeDepth(BinaryTreeNode* pRoot)//計算二叉樹深度
{
if(pRoot==NULL)//如果pRoot為NULL,則深度為0,這也是遞歸的返回條件
return 0;
//如果pRoot不為NULL,那麼深度至少為1,所以left和right=1
int left=1;
int right=1;
left+=TreeDepth(pRoot-m_pLeft);//求出左子樹的深度
right+=TreeDepth(pRoot-m_pRight);//求出右子樹深度
return leftright?left:right;//返回深度較大的那一個
}
void main()
{
// 1
// / \
// 2 3
// /\ \
// 4 5 6
// /
// 7
//創建樹結點
BinaryTreeNode* pNode1 = CreateBinaryTreeNode(1);
BinaryTreeNode* pNode2 = CreateBinaryTreeNode(2);
BinaryTreeNode* pNode3 = CreateBinaryTreeNode(3);
BinaryTreeNode* pNode4 = CreateBinaryTreeNode(4);
BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);
//連接樹結點
ConnectTreeNodes(pNode1, pNode2, pNode3);
ConnectTreeNodes(pNode2, pNode4, pNode5);
ConnectTreeNodes(pNode3, NULL, pNode6);
ConnectTreeNodes(pNode5, pNode7, NULL );
int depth=TreeDepth(pNode1);
coutdepthendl;
system(“pause”);
}
出處:
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/239274.html