列印二叉樹所有的路徑
阿新 • • 發佈:2019-01-03
問題:
給一個二叉樹,把所有的路徑都打印出來。
比如,對於下面這個二叉樹,它所有的路徑為:
8 -> 3 -> 1
8 -> 2 -> 6 -> 4
8 -> 3 -> 6 -> 7
8 -> 10 -> 14 -> 13
思路:
從根節點開始,把自己的值放在一個數組裡,然後把這個陣列傳給它的子節點,子節點同樣把自己的值放在這個數組裡,又傳給自己的子節點,直到這個節點是葉節點,然後把這個陣列打印出來。所以,我們這裡要用到遞迴。
程式碼:
- /**
-
Given a binary tree, prints out all of its root-to-leaf
- paths, one per line. Uses a recursive helper to do the work.
- */
- publicvoid 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.
- */
- privatevoid 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
- 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.
- */
- privatevoid printArray(String[] ints, int len) {
- for (int i = 0; i < len; i++) {
- System.out.print(ints[i] + " ");
- }
- System.out.println();
- }
備註:這裡只能用一個數組+一個數值才能打印出所需要的路徑,如果用linkedlist之類的連結串列結構是不行的。值得分析一下原因,很有意思。