树形遍历(java)---孩子双亲表示法

给定一个树形结构,如图:

将它转换为孩子双亲表示法:

 

以下是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 

 

  

posted on 2016-06-21 23:12  xiezie  阅读(2824)  评论(0编辑  收藏  举报

导航