【问题描述】
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / \ 2 3 \ 5
All root-to-leaf paths are:
["1->2->5", "1->3"]
【思路】
深度优先搜索。
可以递归实现。
【code】
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new LinkedList<String>();
StringBuffer sb = new StringBuffer();
if (root == null) {
return result;
}
Path(root, result, sb);
return result;
}
public void Path(TreeNode root, List<String> result, StringBuffer sb) {
if (root.left == null && root.right == null) {
sb.append(root.val);
result.add(sb.toString());
return;
}
sb.append(root.val);
sb.append("->");
int len = sb.length();
if (root.left!=null) {
Path(root.left, result, sb);
}
sb.setLength(len);
if (root.right!=null) {
Path(root.right, result, sb);
}
}
}