給定一個樹形結構,如圖:
將它轉換為孩子雙親表示法:
以下是JAVA實現://先序遍歷
import java.util.ArrayList; public class TreeTraverse{ static int[] father = { 0,1,1,1,2,2,2,6,6,6,8,4,4,12,13,13,13 }; static int[] child = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17 }; public static void main(String[] arg){ ArrayList<Tree> trees = new ArrayList<>(); trees.add(new Tree(0)); int len = child.length; for(int i = 0 ; i != len ; i ++ ){ trees.add(new Tree(child[i])); } for(int i = 0 ; i != len ; i ++ ){ Tree _father = trees.get(father[i]); if(_father.getFChild()==null){ _father.setFChild(trees.get(child[i])); System.out.println("父親為 " + father[i] + " 大孩子為 " + child[i]); continue; } Tree sibiling = _father.getFChild(); while(sibiling.getChildSibling()!=null){ sibiling = sibiling.getChildSibling(); } sibiling.setChildSibling(trees.get(child[i])); System.out.println("孩子為 " + sibiling.getNum() + " 右兄弟為 " + child[i]); } traverse(trees.get(0)); } static void traverse(Tree father){ if(father.getFChild()==null){ return; } System.out.print(father.getFChild().getNum() + " "); traverse(father.getFChild()); Tree sibiling = father.getFChild(); while(sibiling.getChildSibling()!=null){ sibiling = sibiling.getChildSibling(); System.out.print(sibiling.getNum() + " "); traverse(sibiling); } } static class Tree{ private int num; private Tree fChild; private Tree childSibling; public Tree(int num) { super(); this.num = num; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public Tree getFChild() { return fChild; } public void setFChild(Tree fChild) { this.fChild = fChild; } public Tree getChildSibling() { return childSibling; } public void setChildSibling(Tree sibling) { this.childSibling = sibling; } } }
輸出為:
父親為 0 大孩子為 1
父親為 1 大孩子為 2
孩子為 2 右兄弟為 3
孩子為 3 右兄弟為 4
父親為 2 大孩子為 5
孩子為 5 右兄弟為 6
孩子為 6 右兄弟為 7
父親為 6 大孩子為 8
孩子為 8 右兄弟為 9
孩子為 9 右兄弟為 10
父親為 8 大孩子為 11
父親為 4 大孩子為 12
孩子為 12 右兄弟為 13
父親為 12 大孩子為 14
父親為 13 大孩子為 15
孩子為 15 右兄弟為 16
孩子為 16 右兄弟為 17
1 2 5 6 8 11 9 10 7 3 4 12 14 13 15 16 17