问题:
给一个二叉树,把所有的路径都打印出来。
比如,对于下面这个二叉树,它所有的路径为:
8 -> 3 -> 1
8 -> 2 -> 6 -> 4
8 -> 3 -> 6 -> 7
8 -> 10 -> 14 -> 13
思路:
从根节点开始,把自己的值放在一个数组里,然后把这个数组传给它的子节点,子节点同样把自己的值放在这个数组里,又传给自己的子节点,直到这个节点是叶节点,然后把这个数组打印出来。所以,我们这里要用到递归。
代码:
-
-
-
-
- public void printPaths(Node root, int n) {
- String[] path = new String[n];
- printPaths(root, path, 0);
- }
-
-
-
-
-
- private void printPaths(Node node, String[] path, int pathLen) {
- if (node == null) return;
-
- path[pathLen++] = node.value;
-
- if (node.leftChild == null && node.rightChild == null) {
- printArray(path, pathLen);
- }
- else {
-
- printPaths(node.leftChild, path, pathLen);
- printPaths(node.rightChild, path, pathLen);
- }
- }
-
-
-
- private void printArray(String[] ints, int len) {
- for (int i = 0; i < len; i++) {
- System.out.print(ints[i] + " ");
- }
- System.out.println();
- }
备注:这里只能用一个数组+一个数值才能打印出所需要的路径,如果用linkedlist之类的链表结构是不行的。值得分析一下原因,很有意思。