Java實現(xiàn)打印二叉樹所有路徑的方法
本文實例講述了Java實現(xiàn)打印二叉樹所有路徑的方法。分享給大家供大家參考,具體如下:
問題:
給一個二叉樹,把所有的路徑都打印出來。
比如,對于下面這個二叉樹,它所有的路徑為:
8 -> 3 -> 1
8 -> 2 -> 6 -> 4
8 -> 3 -> 6 -> 7
8 -> 10 -> 14 -> 13
思路:
從根節(jié)點開始,把自己的值放在一個數(shù)組里,然后把這個數(shù)組傳給它的子節(jié)點,子節(jié)點同樣把自己的值放在這個數(shù)組里,又傳給自己的子節(jié)點,直到這個節(jié)點是葉節(jié)點,然后把這個數(shù)組打印出來。所以,我們這里要用到遞歸。
代碼:
/** Given a binary tree, prints out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work. */ public void printPaths(Node root, int n) { String[] path = new String[n]; printPaths(root, path, 0); } /** Recursive printPaths helper -- given a node, and an array containing the path from the root node up to but not including this node, prints out all the root-leaf paths. */ private void printPaths(Node node, String[] path, int pathLen) { if (node == null) return; // append this node to the path array path[pathLen++] = node.value; // it's a leaf, so print the path that led to here if (node.leftChild == null && node.rightChild == null) { printArray(path, pathLen); } else { // otherwise try both subtrees printPaths(node.leftChild, path, pathLen); printPaths(node.rightChild, path, pathLen); } } /** Utility that prints strings from an array on one line. */ private void printArray(String[] ints, int len) { for (int i = 0; i < len; i++) { System.out.print(ints[i] + " "); } System.out.println(); }
備注:這里只能用一個數(shù)組+一個數(shù)值才能打印出所需要的路徑,如果用linkedlist之類的鏈表結(jié)構(gòu)是不行的。值得分析一下原因,很有意思。
更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
Spring boot基于ScheduledFuture實現(xiàn)定時任務
這篇文章主要介紹了Spring boot基于ScheduledFuture實現(xiàn)定時任務,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06Java 常見異常(Runtime Exception )詳細介紹并總結(jié)
這篇文章主要介紹了Java 常見異常(Runtime Exception )詳細介紹并相關(guān)資料,大家在開發(fā)Java 應用軟件的時候經(jīng)常會遇到各種異常這里幫大家整理了一部分,并解釋如何解決,需要的朋友可以參考下2016-10-10SpringBoot使用AOP,內(nèi)部方法失效的解決方案
這篇文章主要介紹了SpringBoot使用AOP,內(nèi)部方法失效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08Mybatis核心配置文件、默認類型別名、Mybatis獲取參數(shù)值的兩種方式(實例代碼)
這篇文章主要介紹了Mybatis核心配置文件、默認類型別名、Mybatis獲取參數(shù)值的兩種方式,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-03-03Java簡單計時的實現(xiàn)案例(可以用來限時循環(huán))
這篇文章主要介紹了Java簡單計時的實現(xiàn)案例(可以用來限時循環(huán)),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08關(guān)于SpringBoot單元測試(cobertura生成覆蓋率報告)
這篇文章主要介紹了關(guān)于SpringBoot單元測試(cobertura生成覆蓋率報告),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11