어흥

[해커랭크] Preorder, Inorder, Postorder traversal (C++) 본문

알고리즘/HackerRank

[해커랭크] Preorder, Inorder, Postorder traversal (C++)

라이언납시오 2021. 1. 20. 15:22
728x90
반응형

문제링크:

[Preorder] www.hackerrank.com/challenges/tree-preorder-traversal/problem?h_r=internal-search

 

Tree: Preorder Traversal | HackerRank

Print the preorder traversal of a binary tree.

www.hackerrank.com

[Inorder] www.hackerrank.com/challenges/tree-inorder-traversal/problem?h_r=internal-search

 

Tree: Inorder Traversal | HackerRank

Print the inorder traversal of a binary tree.

www.hackerrank.com

[Postorder] www.hackerrank.com/challenges/tree-postorder-traversal/problem?h_r=internal-search

 

Tree: Postorder Traversal | HackerRank

Print the post order traversal of a binary tree.

www.hackerrank.com

1. 주의할 점

- 전위, 중위, 후위 순회의 출력 순서에 대해 알고 있어야 한다

 

2. 구현

[Preorder] : Root->Left->Right

void preOrder(Node *root) {
    cout << root->data<<" ";
    if(root->left!=NULL){
        preOrder(root->left);
    }
    if(root->right!=NULL){
        preOrder(root->right);
    }
}

[Inorder] : Left->Root->Right

void InOrder(Node *root) {
    if(root->left!=NULL){
        preOrder(root->left);
    }
    cout << root->data<<" ";
    if(root->right!=NULL){
        preOrder(root->right);
    }
}

[Postorder] : Left->Right->Root

void postOrder(Node *root) {
    if(root->left!=NULL){
        preOrder(root->left);
    }
    if(root->right!=NULL){
        preOrder(root->right);
    }
    cout << root->data<<" ";
}
728x90
반응형
Comments