java 樹和森林操作

生成一棵樹

例如有l(wèi)ist 數(shù)組,需要整理成森林
public class Tree {
    private Integer id;
    private String code;
    private String name;
    protected Integer pid;
    private List<Tree> children;
}

 public static List<Tree> initByList() {
        List<Tree> lists = new ArrayList<>();
        // 第一層的節(jié)點(diǎn)
        lists.add(new Tree(1, 0));
        // 第二層的節(jié)點(diǎn)
        lists.add(new Tree(11, 1));
        lists.add(new Tree(12, 1));
        lists.add(new Tree(13, 1));
        // 第三層的節(jié)點(diǎn)
        lists.add(new Tree(111, 11));
        lists.add(new Tree(112, 11));
        lists.add(new Tree(113, 11));
        lists.add(new Tree(114, 11));
        lists.add(new Tree(115, 11));
        lists.add(new Tree(116, 11));
        lists.add(new Tree(121, 12));
        lists.add(new Tree(122, 12));
        lists.add(new Tree(123, 12));
        // 第四層的節(jié)點(diǎn)
        lists.add(new Tree(1131, 113));
        lists.add(new Tree(1132, 113));
        lists.add(new Tree(1161, 116));
        lists.add(new Tree(1231, 123));
        lists.add(new Tree(1232, 123));
        //另一顆樹
        // 第一層的節(jié)點(diǎn)
        lists.add(new Tree(2, 0));
        // 第二層的節(jié)點(diǎn)
        lists.add(new Tree(21, 2));
        lists.add(new Tree(22, 2));
        lists.add(new Tree(23, 2));
        Collections.shuffle(lists);
        return  lists;
    }

整理一棵樹有兩個(gè)思路雅镊,根據(jù)父親找兒子吹缔、根據(jù)兒子找父親。

根據(jù)父親找兒子
    //找兒子: 根據(jù)條件 整理一棵森林
    public static List<Tree> organizationByCondition(List<Tree> trees, Predicate<Tree> rootPredicate) {
        List<Tree> roots = new ArrayList<>();
        for (Tree tree : trees) {
            //是 root 節(jié)點(diǎn)
            if (rootPredicate.test(tree)) {
                roots.add(organizationByRoot(trees,tree));
            }
        }
        return roots;
    }

    //找兒子: 根據(jù)根節(jié)點(diǎn) 整理一棵樹
    private static Tree organizationByRoot(List<Tree> trees, Tree root) {
        //需要找兒子節(jié)點(diǎn)的集合
        Queue<Tree> immediately = new ArrayDeque<>();
        immediately.add(root);
        while (!immediately.isEmpty()) {
            Tree t = immediately.poll();
            for (Tree c : trees) {
                if (Objects.equals(c.getPid(), t.getId())) {
                    t.getChildren().add(c);
                    //如果找到了孩子耕挨,那么添加到隊(duì)列繼續(xù)找孩子的孩子
                    immediately.add(c);
                }
            }
        }
        return root;
    }
根據(jù)兒子找父親
    //找父親:根據(jù)條件 整理一棵森林
    public static List<Tree> organization(List<Tree> trees) {
        List<Tree> roots = new ArrayList<>();
        Queue<Tree> chaos = new ArrayDeque<>(trees);
        //查找自己的父親
        while (!chaos.isEmpty()) {
            Tree t = chaos.poll();
            if (!findParent(trees, t)) {
                //沒有父親節(jié)點(diǎn)那么,認(rèn)為是根節(jié)點(diǎn)
                roots.add(t);
            }
            //此處可處理排序問題
        }
        return roots;
    }

    private static boolean findParent(List<Tree> immediately, Tree t) {
        for (Tree parent : immediately) {
            if (Objects.equals(parent.getId(), t.getPid())) {
                parent.getChildren().add(t);
                return true;
            }
        }
        return false;
    }

將一顆樹重新變換回list

    /**
     * 換成list
     */
    public List<Tree> treeToList(Tree init) {
        List<Tree> R = new ArrayList<>();
        //先進(jìn)先出
        Queue<Tree> queue = new ArrayDeque<>();
        queue.add(init);
        while (!queue.isEmpty()) {
            Tree poll = queue.poll();
            R.add(poll);
            System.out.println(poll.getName());
            List<Tree> children = poll.getChildren();
            if (children == null || children.isEmpty()) {
                continue;
            }
            for (Tree child : children) {
                if (child != null)
                    queue.add(child);
            }
        }
        return R;
    }

查找符合條件的節(jié)點(diǎn)

   /**
     * 查找一個(gè)符合條件的節(jié)點(diǎn)
     */
    public Tree findOneByCondition(Tree init, Predicate<Tree> predicate1) {
        //先進(jìn)先出
        Queue<Tree> queue = new ArrayDeque<>();
        queue.add(init);
        while (!queue.isEmpty()) {
            Tree poll = queue.poll();
            if (predicate1.test(poll)) return poll;
            List<Tree> children = poll.getChildren();
            if (children == null || children.isEmpty()) {
                continue;
            }
            for (Tree child : children) {
                if (child != null)
                    queue.add(child);
            }
        }
        return null;
    }


    /**
     * 查找所有符合條件的節(jié)點(diǎn)
     */
    public List<Tree> findListByCondition(Tree init, Predicate<Tree> predicate1) {
        List<Tree> r = new ArrayList<>();
        //先進(jìn)先出
        Queue<Tree> queue = new ArrayDeque<>();
        queue.add(init);
        while (!queue.isEmpty()) {
            Tree poll = queue.poll();
            if (predicate1.test(poll)) {
                r.add(poll);
            }
            List<Tree> children = poll.getChildren();
            if (children == null || children.isEmpty()) {
                continue;
            }
            for (Tree child : children) {
                if (child != null)
                    queue.add(child);
            }
        }
        return r;
    }

查找指定層級(jí): 這個(gè)需要兩個(gè)隊(duì)列分別存放父親、兒子集合尉桩。然后來回交換筒占,每交換一次,即一層遍歷結(jié)束蜘犁。

/**
     * 查找指定層級(jí)的節(jié)點(diǎn)
     */
    public Map<Integer, List<Tree>> findByLevel(Tree init, Predicate<Integer> predicate) {
        Map<Integer, List<Tree>> R = new HashMap<>();
        //如果需要獲取第一個(gè)
        if (predicate.test(0)) {
            putAvoidNull(R, 0, init);
        }
        Queue<Tree> parent = new ArrayDeque<>();
        Queue<Tree> children = new ArrayDeque<>();
        parent.add(init);
        int layer = 0;
        while (!parent.isEmpty() || !children.isEmpty()) {
            if (!parent.isEmpty()) { // parent隊(duì)列不為空時(shí), 將頭節(jié)點(diǎn)的子節(jié)點(diǎn)放入children隊(duì)列.
                Tree node = parent.poll();
                if (node.getChildren() != null) {
                    node.getChildren().forEach(child -> children.add(child));
                }
            } else {
                layer++;
                for (Tree child : children) {
                    if (predicate.test(layer)) {
                        putAvoidNull(R, layer, child);
                    }
                }
                // 將parent隊(duì)列替換為children 隊(duì)列
                parent.addAll(children);
                // 清空children隊(duì)列
                children.clear();
            }
        }
        return R;
    }

查找樹的全路徑:有兩種方法1 遞歸 2非遞歸方法

遞歸方式不推薦
   /**
     * 根據(jù)查詢條件, 縱向查找全路徑
     */
    public void findPathByCondition(Tree root, String path, List<String> pathList, Predicate<Tree> predicate1) {
        //已經(jīng)查找到退出循環(huán)
        if (!pathList.isEmpty()) {
            return;
        }
        if (predicate1.test(root)) {
            path = path + root.getName();
            pathList.add(path); //將結(jié)果保存在list中
        } else { //非葉子節(jié)點(diǎn)
            path = path + "/" + root.getName(); //進(jìn)行子節(jié)點(diǎn)的遞歸
            List<Tree> iterator = root.getChildren();
            for (Tree tree : iterator) {
                findPathByCondition(tree, path, pathList, predicate1);
            }
        }
    }
推薦非遞歸方式
   /**
     * 非遞歸版本
     *
     * @param root
     * @param predicate
     * @return
     */
    public static List<Tree> findPath(Tree root, Predicate<Tree> predicate) {
        if (root == null) {
            return null;
        }
        Stack<Tree> path = new Stack<>();
        int level = 0;
        //支持最大100層 index 是層數(shù),  value 元素?cái)?shù)量
        int[] layer = new int[100];
        Stack<Tree> s = new Stack<>();
        s.push(root);
        //根節(jié)點(diǎn)是第0層
        layer[level]++;
        while (!s.isEmpty()) {
            //查找仍有數(shù)據(jù)的層
            while (layer[level] < 1){
                level--;
                path.pop();
            }
           Tree temp = s.pop();
            path.push(temp);
            //已經(jīng)找到該節(jié)點(diǎn)
            if (predicate.test(temp)) {
                return path;
            }
            //記錄當(dāng)前層元素?cái)?shù)量
            layer[level]--;
            List<Tree> children = temp.getChildren();
            if (children == null || children.isEmpty()) {
                path.pop();
                continue;
            }
            level++;
            //遞歸子節(jié)點(diǎn)
            for (Tree child : children) {
                s.push(child);
                layer[level]++;
            }
        }
        return null;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末翰苫,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子这橙,更是在濱河造成了極大的恐慌奏窑,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,104評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件屈扎,死亡現(xiàn)場(chǎng)離奇詭異埃唯,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)鹰晨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門墨叛,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人模蜡,你說我怎么就攤上這事漠趁。” “怎么了哩牍?”我有些...
    開封第一講書人閱讀 168,697評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵棚潦,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我膝昆,道長(zhǎng)丸边,這世上最難降的妖魔是什么叠必? 我笑而不...
    開封第一講書人閱讀 59,836評(píng)論 1 298
  • 正文 為了忘掉前任,我火速辦了婚禮妹窖,結(jié)果婚禮上纬朝,老公的妹妹穿的比我還像新娘。我一直安慰自己骄呼,他們只是感情好共苛,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,851評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蜓萄,像睡著了一般隅茎。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上嫉沽,一...
    開封第一講書人閱讀 52,441評(píng)論 1 310
  • 那天辟犀,我揣著相機(jī)與錄音,去河邊找鬼绸硕。 笑死堂竟,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的玻佩。 我是一名探鬼主播出嘹,決...
    沈念sama閱讀 40,992評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼咬崔!你這毒婦竟也來了税稼?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,899評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤刁赦,失蹤者是張志新(化名)和其女友劉穎娶聘,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體甚脉,經(jīng)...
    沈念sama閱讀 46,457評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,529評(píng)論 3 341
  • 正文 我和宋清朗相戀三年铆农,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了牺氨。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,664評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡墩剖,死狀恐怖猴凹,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情岭皂,我是刑警寧澤郊霎,帶...
    沈念sama閱讀 36,346評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站爷绘,受9級(jí)特大地震影響书劝,放射性物質(zhì)發(fā)生泄漏进倍。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,025評(píng)論 3 334
  • 文/蒙蒙 一购对、第九天 我趴在偏房一處隱蔽的房頂上張望猾昆。 院中可真熱鬧,春花似錦骡苞、人聲如沸垂蜗。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽贴见。三九已至,卻和暖如春躲株,著一層夾襖步出監(jiān)牢的瞬間片部,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工徘溢, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留吞琐,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,081評(píng)論 3 377
  • 正文 我出身青樓然爆,卻偏偏與公主長(zhǎng)得像站粟,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子曾雕,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,675評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • 遞歸 一棵樹要么是空樹奴烙,要么有兩個(gè)指針,每個(gè)指針指向一棵樹剖张。樹是一種遞歸結(jié)構(gòu)切诀,很多樹的問題可以使用遞歸來處理。 1...
    奔向星辰大海閱讀 810評(píng)論 0 0
  • 表搔弄、棧和隊(duì)列 表 我們處理形如A0,A1,.....,AN的一般的表幅虑。我們說這個(gè)表的大小是N。我們將大小為0 的特...
    tanghomvee閱讀 752評(píng)論 0 0
  • 目錄 1 時(shí)間復(fù)雜度 2 樹 3 散列 4 優(yōu)先級(jí)隊(duì)列(堆) 5 排序 6 圖參考資料 · 《數(shù)據(jù)結(jié)...
    小小千千閱讀 907評(píng)論 0 0
  • 目錄 0.樹0.1 一般樹的定義0.2 二叉樹的定義 1.查找樹ADT 2.查找樹的實(shí)現(xiàn)2.1 二叉查找樹2.2 ...
    王偵閱讀 7,249評(píng)論 0 3
  • 樹 在n個(gè)結(jié)點(diǎn)的樹中有n-1條邊擎宝。樹中一個(gè)結(jié)點(diǎn)的子結(jié)點(diǎn)個(gè)數(shù)稱為該結(jié)點(diǎn)的度,樹中結(jié)點(diǎn)的最大度數(shù)稱為樹的度浑玛。有序樹和無...
    我好菜啊_閱讀 848評(píng)論 0 0