Create Binary Tree
- Binary Tree struct define
typedef struct BinaryTreeNodeStru
{
char dataValue;
struct BinaryTreeNodeStru* leftNode{NULL};
struct BinaryTreeNodeStru* rightNode{NULL};
}BinaryTreeNode, *BinaryTreeRoot;
- Binary Tree Create
void CreateBinaryTree(BinaryTreeRoot& biTree, char* &pValue, int& nodeNumber)
{
if (0 == nodeNumber)
{
biTree = nullptr;
return;
}
char c = *pValue;
if ('#' == c )
{
biTree = nullptr;
return;
}
biTree = new BinaryTreeNode;
biTree->dataValue = c;
nodeNumber--;
pValue++;
CreateBinaryTree(biTree->leftNode, pValue, nodeNumber);
if (nodeNumber > 0)
{
nodeNumber--;
pValue++;
CreateBinaryTree(biTree->rightNode, pValue, nodeNumber);
}
return;
}
- Binary Depth
int TreeDepth(BinaryTreeNode* biTreeNode)
{
int lefeDepdenth;
int rightDepdenth;
if ( NULL == biTreeNode)
{
return 0;
}
lefeDepdenth = TreeDepth(biTreeNode->leftNode);
rightDepdenth = TreeDepth(biTreeNode->rightNode);
return (lefeDepdenth >rightDepdenth ? lefeDepdenth+1 : rightDepdenth+1);
}
test codes
void BinaryTreeTest()
{
BinaryTreeRoot biTree = nullptr;
char biTreeValue[10] = {'1', '2', '3','4','#', '#', '5', '6', '#', '#'};
int NodeNumber = 10;
char* pbiTreeValue = biTreeValue;
CreateBinaryTree(biTree, pbiTreeValue, NodeNumber);
int treeDepth = 0;
treeDepth = TreeDepth(biTree);
printf("tree depth is %d .",treeDepth);
return;
}
网友评论