Skip to content

Commit 9d88ad9

Browse files
author
yangjunbao
committed
二叉树根节点的所有路径打印
1 parent 892c452 commit 9d88ad9

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package com.apptao.leetcode.tree;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* 写一个算法,得出二叉树所有根节点到叶子节点的路径
8+
* Created by a on 2017-12-28.
9+
* <p>
10+
* 例如:
11+
* 1
12+
* / \
13+
* 2 3
14+
* \
15+
* 5
16+
* 结果:
17+
* <p>
18+
* ["1->2->5", "1->3"]
19+
*/
20+
public class BinaryTreePaths {
21+
22+
public class TreeNode {
23+
int val;
24+
TreeNode leftChild;
25+
TreeNode rightChild;
26+
27+
TreeNode(int x) {
28+
val = x;
29+
}
30+
}
31+
32+
/**
33+
* 创建一棵二叉树
34+
* <pre>
35+
* 1
36+
* 2 3
37+
* 4 5 6
38+
* </pre>
39+
*/
40+
public TreeNode createBinTree() {
41+
TreeNode root = new TreeNode(1);
42+
TreeNode newNode2 = new TreeNode(2);
43+
TreeNode newNode3 = new TreeNode(3);
44+
TreeNode newNode4 = new TreeNode(4);
45+
TreeNode newNode5 = new TreeNode(5);
46+
TreeNode newNode6 = new TreeNode(6);
47+
root.leftChild = newNode2;
48+
root.rightChild = newNode3;
49+
root.leftChild.leftChild = newNode4;
50+
root.leftChild.rightChild = newNode5;
51+
root.rightChild.rightChild = newNode6;
52+
return root;
53+
}
54+
55+
public static void main(String[] args) {
56+
57+
BinaryTreePaths binaryTreePaths = new BinaryTreePaths();
58+
59+
List<String> strings = binaryTreePaths.binaryTreePaths(binaryTreePaths.createBinTree());
60+
61+
System.out.println(strings.toString());
62+
}
63+
64+
/**
65+
* 接收数据进行处理,求二叉树的路径
66+
* @param root TreeNode
67+
* @return list
68+
*/
69+
public List<String> binaryTreePaths(TreeNode root) {
70+
List<String> result = new ArrayList<>();
71+
new BinaryTreePaths().inorder(root, result, "");
72+
return result;
73+
}
74+
75+
/**
76+
* 递归路径,添加到list
77+
* @param node TreeNode
78+
* @param list List<String>
79+
* @param path String
80+
*/
81+
private void inorder(TreeNode node, List<String> list, String path) {
82+
if (node != null) {
83+
if (node.leftChild == null && node.rightChild == null) {
84+
list.add(path + node.val);
85+
} else {
86+
inorder(node.leftChild, list, path + node.val + "->");
87+
inorder(node.rightChild, list, path + node.val + "->");
88+
}
89+
}
90+
}
91+
92+
93+
}

0 commit comments

Comments
 (0)