激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Java實現打印二叉樹所有路徑的方法

Java實現打印二叉樹所有路徑的方法

2021-04-05 12:33sam_justin Java教程

這篇文章主要介紹了Java實現打印二叉樹所有路徑的方法,涉及java二叉樹遍歷與運算相關操作技巧,需要的朋友可以參考下

本文實例講述了Java實現打印二叉樹所有路徑的方法。分享給大家供大家參考,具體如下:

問題:

給一個二叉樹,把所有的路徑都打印出來。

比如,對于下面這個二叉樹,它所有的路徑為:

8 -> 3 -> 1
8 -> 2 -> 6 -> 4
8 -> 3 -> 6 -> 7
8 -> 10 -> 14 -> 13

Java實現打印二叉樹所有路徑的方法

思路:

從根節點開始,把自己的值放在一個數組里,然后把這個數組傳給它的子節點,子節點同樣把自己的值放在這個數組里,又傳給自己的子節點,直到這個節點是葉節點,然后把這個數組打印出來。所以,我們這里要用到遞歸。

代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
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();
}

備注:這里只能用一個數組+一個數值才能打印出所需要的路徑,如果用linkedlist之類的鏈表結構是不行的。值得分析一下原因,很有意思。

希望本文所述對大家java程序設計有所幫助。

原文鏈接:http://blog.csdn.net/samjustin1/article/details/52561831

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 色戒在线版| 热久久成人 | 黄在线观看在线播放720p | 成人国产精品齐天大性 | 精品国产一级毛片 | 久久国产精品二国产精品中国洋人 | 日韩中文字幕三区 | 欧美色视频免费 | 亚州综合图片 | 欧美另类视频在线 | 国产亚洲综合一区二区 | 91精品免费观看 | www.99xxxx.com| 国产福利视频在线观看 | 蜜桃传免费看片www 一本色道精品久久一区二区三区 | 久久精品高清 | 国产一区二区欧美精品 | 久久精品免费国产 | 国产一区日韩一区 | 俄罗斯16一20sex牲色另类 | caoporn国产一区二区 | 免费一级毛片在线播放视频老 | 久久精品无码一区二区日韩av | 国产精品久久久久免费视频 | 在线观看免费精品 | 91看片在线看 | 一级毛片在线视频 | 99精品视频在线观看免费 | 毛片视频网站在线观看 | 大胆在线日本aⅴ免费视频 美国黄色毛片女人性生活片 | 综合在线视频 | 成人免费一区二区三区在线观看 | 一级在线| 日日摸夜夜添夜夜添牛牛 | 久久久久久久亚洲精品 | 国产毛片视频 | 亚洲一区在线免费视频 | 久久久一区二区三区精品 | 精品一区二区三区免费看 | 亚洲天堂在线电影 | 午夜精品成人 |