본문 바로가기
Algorithm/Recursion

[Recursion/C++] 이진트리 재귀 알고리즘 size(), height(), mirror(), sumOfWeight(), maxPathWeight()

by @__100.s 2021. 10. 27.
반응형

size()

 

int treeSize(node *root)  {
    int size=0;
    if( root != NULL )
        size = 1 + treeSize(root->leftSubtree)+ treeSize(root->rightSubtree);
    return size;
}

 

height()

int treeHeight(node *root){
    int height=0;
    if( root != NULL )
        height = 1 + max(treeHeight(root->leftSubtree),treeHeight(root->rightSubtree));
    return height;
}

 

mirror()

void mirror(node *root)
{
    if (root == NULL)
        return;
    else
    {
        struct node *temp;

        mirror(root->leftSubtree);
        mirror(root->rightSubtree);

        temp = root->leftSubtree;
        root ->leftSubtree = root->rightSubtree;
        root->rightSubtree = temp;
    }
}

 

sumOfWeight()

int sumOfWeight(struct node *root)
{
        if(root == NULL)
            return 0;
        else
            return sumOfWeight(root‐>leftSubTree)+sumOfWeight(root‐>rightSubTree)+ root‐>weight;
}

 

maxPathWeight()

int maxPathWeight(struct node *root)
{
        if(root == NULL)
            return 0;
        else {
                int leftWeight, rightWeight;
                leftWeight = maxPathWeight(root‐>leftSubTree);
                rightWeidght = maxPathWeight(root‐>rightSubTree);
                return root‐>weight + leftWeight >= rightWeight ? leftWeight : rightWeight;
        }
}
반응형