DINGA DINGA
article thumbnail
728x90

www.hackerrank.com/challenges/tree-postorder-traversal/problem

 

Tree: Postorder Traversal | HackerRank

Print the post order traversal of a binary tree.

www.hackerrank.com

Data Structures > Trees

 

트리가 주어지면 postorder로 출력하는 함수 postOrder()를 작성한다.

 

 

코드

void postOrder( struct node *root) {
    struct node *temp;
    temp = root;
    if (temp){
        if (temp->left)
            postOrder(temp->left);
        if (temp->right)
            postOrder(temp->right);
        printf("%d ", temp->data);
    }
}

 

설명

노드가 NULL이 아닐 때 아래를 실행한다.

만약 루트 노드의 left가 NULL이 아니라면 루트 노드의 left에 대하여 postOrder 함수를 호출한다.

이렇게 재귀적으로 루트 노드의 left의 모든 노드를 따라 내려가 단말 노드에 도달하면, 다시 거슬러 올라가며 노드의 데이터들을 출력한다.

출력이 끝나고 루트 노드에 도달하면 다시 루트 노드의 right에 대해 같은 과정을 반복한다.

 

728x90