๋ฐ์ํ
์๋์ ์์์ ๋ฐํ์ผ๋ก ์์ฑ๋์์ต๋๋ค. ์ข์์์ ๊ฐ์ฌํฉ๋๋ค.
[์๋ฃ๊ตฌ์กฐ ์๊ณ ๋ฆฌ์ฆ] ์ด์ง๊ฒ์ํธ๋ฆฌ์์ ๋ค์๋
ธ๋ ์ฐพ๊ธฐ (inorder traverse)
https://youtu.be/6DIxzakjewQ
(1) .h
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <iostream> | |
#include <vector> | |
using namespace std; | |
class Node | |
{ | |
public: | |
int data; | |
Node* left, * right, *parent; | |
Node(int data) { | |
this->data = data; | |
this->left = this->right = this->parent= NULL; | |
} | |
}; | |
class Tree | |
{ | |
public: | |
Node* root = NULL; | |
Tree(vector<int> a) | |
{ | |
root = bst(a, 0, a.size() - 1, NULL); | |
//root->right->right->right->right = new Node(-1); | |
} | |
Node* bst(vector<int> a, int start, int end, Node* parent) | |
{ | |
if (start <= end) | |
{ | |
int mid = (start + end) / 2; | |
Node* newNode = new Node(a[mid]); | |
newNode->left = bst(a, start, mid - 1, newNode); | |
newNode->right = bst(a, mid + 1, end, newNode); | |
newNode->parent = parent; | |
return newNode; | |
} | |
return NULL; | |
} | |
//์ด์ง๊ฒ์ํธ๋ฆฌ์์ | |
//์ฃผ์ด์ง ๋ ธ๋์ ๋ค์๋ ธ๋๋ฅผ | |
//์ฐพ๋ ํจ์๋ฅผ ๊ตฌํ(inorder์ ์ ๊ฐํจ) | |
void findNextNode(Node* node) | |
{ | |
if (node->right == NULL) | |
{ | |
cout << findAbove(node->parent, node)->data << " is " << | |
node->data << "'s next" << endl; | |
} | |
else | |
{ | |
cout << findBelow(node->right)->data << " is " << | |
node->data << "'s next" << endl; | |
} | |
} | |
Node* findAbove(Node* parent, Node* child)//๋ถ๋ชจ๋ฅผ ์ฐพ๋๋ค | |
{ | |
if (parent == NULL) return NULL; | |
if (parent->left == child) return parent; | |
else return findAbove(parent->parent, parent); | |
} | |
Node* findBelow(Node* node)//left๋ฅผ ์ฐพ๋๋ค | |
{ | |
if (node->left == NULL) return node; | |
else return findBelow(node->left); | |
} | |
}; |
(2) .cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "header.h" | |
int main() { | |
//์ ๋ ฌ ๋์ด์๋ ๋ฐฐ์ด์ ๋ฃ๋๋ค | |
Tree* t = new Tree({ 0,1,2,3,4,5,6,7,8,9 }); | |
//4 is 3's next | |
t->findNextNode(t->root->left->right->right); | |
return 0; | |
} |
๋ฐ์ํ