# LeetCode算法题-Binary Tree Paths（Java实现-3种解法）

### 01 看题和准备

  1
/ \
2   3
\
5

### 02 第一种解法

public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<String>();
if (root == null) {
return list;
}
helperFun(root, list, "");
return list;
}

public void helperFun(TreeNode root, List<String> list, String path) {
if (root.left != null) {
helperFun(root.left, list, path + root.val + "->");
}
if (root.right != null) {
helperFun(root.right, list, path + root.val + "->");
}
if (root.left == null && root.right == null) {
}
}

### 03 第二种解法

public List<String> binaryTreePaths2(TreeNode root) {
List<String> list = new ArrayList<String>();
if (root == null) {
return list;
}
if (root.left == null && root.right == null) {
return list;
}
for (String path : binaryTreePaths(root.left)) {
}
for (String path : binaryTreePaths(root.right)) {
}
return list;
}

### 04 第三种解法

public List<String> binaryTreePaths3(TreeNode root) {
List<String> list = new ArrayList<String>();
Stack<TreeNode> sNode = new Stack<TreeNode>();
Stack<String> sStr = new Stack<String>();
if (root == null){
return list;
}
sNode.push(root);
sStr.push("");
while (!sNode.isEmpty()) {
TreeNode curNode = sNode.pop();
String curStr = sStr.pop();
if (curNode.left == null && curNode.right == null) {
}
if (curNode.left != null) {
sNode.push(curNode.left);
sStr.push(curStr + curNode.val + "->");
}
if (curNode.right != null) {
sNode.push(curNode.right);
sStr.push(curStr + curNode.val + "->");
}
}
return list;
}

### 05 小结

posted @ 2018-12-12 08:16 小川94 阅读(...) 评论(...) 编辑 收藏