์ด์ง ๊ฒ์ ํธ๋ฆฌ๋ ๋ค์๊ณผ ๊ฐ์ ์ธ ๊ฐ์ง ์กฐ๊ฑด์ ๋ง์กฑํ๋ ์ด์ง ํธ๋ฆฌ์ด๋ค.
- ๋ ธ๋์ ์ผ์ชฝ ์๋ธํธ๋ฆฌ์ ์๋ ๋ชจ๋ ๋ ธ๋์ ํค๋ ๋ ธ๋์ ํค๋ณด๋ค ์๋ค.
- ๋ ธ๋์ ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ์ ์๋ ๋ชจ๋ ๋ ธ๋์ ํค๋ ๋ ธ๋์ ํค๋ณด๋ค ํฌ๋ค.
- ์ผ์ชฝ, ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๋ ์ด์ง ๊ฒ์ ํธ๋ฆฌ์ด๋ค.
์ ์ ์ํ (๋ฃจํธ-์ผ์ชฝ-์ค๋ฅธ์ชฝ)์ ๋ฃจํธ๋ฅผ ๋ฐฉ๋ฌธํ๊ณ , ์ผ์ชฝ ์๋ธํธ๋ฆฌ, ์ค๋ฅธ์ชฝ ์๋ธ ํธ๋ฆฌ๋ฅผ ์์๋๋ก ๋ฐฉ๋ฌธํ๋ฉด์ ๋ ธ๋์ ํค๋ฅผ ์ถ๋ ฅํ๋ค. ํ์ ์ํ (์ผ์ชฝ-์ค๋ฅธ์ชฝ-๋ฃจํธ)๋ ์ผ์ชฝ ์๋ธํธ๋ฆฌ, ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ, ๋ฃจํธ ๋ ธ๋ ์์๋๋ก ํค๋ฅผ ์ถ๋ ฅํ๋ค.
์๋ฅผ ๋ค์ด, ์์ ์ด์ง ๊ฒ์ ํธ๋ฆฌ์ ์ ์ ์ํ ๊ฒฐ๊ณผ๋ 50 30 24 5 28 45 98 52 60 ์ด๊ณ , ํ์ ์ํ ๊ฒฐ๊ณผ๋ 5 28 24 45 30 60 52 98 50 ์ด๋ค.
์ด์ง ๊ฒ์ ํธ๋ฆฌ๋ฅผ ์ ์ ์ํํ ๊ฒฐ๊ณผ๊ฐ ์ฃผ์ด์ก์ ๋, ์ด ํธ๋ฆฌ๋ฅผ ํ์ ์ํํ ๊ฒฐ๊ณผ๋ฅผ ๊ตฌํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค.
์ ๋ ฅ
ํธ๋ฆฌ๋ฅผ ์ ์ ์ํํ ๊ฒฐ๊ณผ๊ฐ ์ฃผ์ด์ง๋ค. ๋ ธ๋์ ๋ค์ด์๋ ํค์ ๊ฐ์ 106๋ณด๋ค ์์ ์์ ์ ์์ด๋ค. ๋ชจ๋ ๊ฐ์ ํ ์ค์ ํ๋์ฉ ์ฃผ์ด์ง๋ฉฐ, ๋ ธ๋์ ์๋ 10,000๊ฐ ์ดํ์ด๋ค. ๊ฐ์ ํค๋ฅผ ๊ฐ์ง๋ ๋ ธ๋๋ ์๋ค.
์ถ๋ ฅ
์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง ์ด์ง ๊ฒ์ ํธ๋ฆฌ๋ฅผ ํ์ ์ํํ ๊ฒฐ๊ณผ๋ฅผ ํ ์ค์ ํ๋์ฉ ์ถ๋ ฅํ๋ค.
ํธ๋ฆฌ ํด๋์ค๋ฅผ ์ ๊ตฌํํ๋ ๊ฒ ํต์ฌ
๐ก ๊ฐ์ด root๋ณด๋ค ์๋ค๋ฉด root.left์ ์ ์ฅ
๐ก ๊ฐ์ด root๋ณด๋ค ํฌ๋ค๋ฉด root.right์ ์ ์ฅ
๐ก postorderํจ์ ๊ตฌํ
1) ๊ฐ์ด root๋ณด๋ค ์๋ค๋ฉด root.left์ ์ ์ฅ
if(cur.value > value)
cur.left = addNode(cur.left, value);
else if (cur.value < value)
cur.right = addNode(cur.right, value);
static void postorder(TreeNode root) {
if(root.left != null)
postorder(root.left);
if(root.right != null)
postorder(root.right);
System.out.println(root.value);
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Graph_7 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
TreeNode root = new TreeNode(Integer.parseInt(br.readLine()));
while(true) {
String num = br.readLine();
if(num == null || num.length() == 0)
break;
root = root.addNode(root, Integer.parseInt(num));
}
postorder(root);
}
static class TreeNode{
int value;
TreeNode left;
TreeNode right;
TreeNode(int value){
this.value = value;
}
TreeNode addNode(TreeNode cur, int value) {
if(cur == null)
return new TreeNode(value);
if(cur.value > value)
cur.left = addNode(cur.left, value);
else if (cur.value < value)
cur.right = addNode(cur.right, value);
return cur;
}
}
static void postorder(TreeNode root) {
if(root.left != null)
postorder(root.left);
if(root.right != null)
postorder(root.right);
System.out.println(root.value);
}
}
์ฑ๊ณตโจ