美文网首页
Binary Tree Depth

Binary Tree Depth

作者: zxlele_c763 | 来源:发表于2021-05-23 17:34 被阅读0次

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

相关文章

网友评论

      本文标题:Binary Tree Depth

      本文链接:https://www.haomeiwen.com/subject/lhszjltx.html