深度优先搜索思路
1、结果是输出一个记录了路径的集合paths 该集合泛型为String类
2、深度遍历二叉树
3、定义StringBuffer类型的字符串 pathSB,它的好处是可以append()方法灵活扩充
4、如果当前节点不是叶子节点,pathSB拼接一个"->",并把当前节点的值加入进pathSB
5、如果当前节点是叶子节点,就把pathSB加入paths
6、左、右节点不停递归,最后输出paths
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
//深度优先遍历
List<String> paths = new ArrayList<String>();
dfs(root,"",paths);
return paths;
}
public void dfs(TreeNode root, String path,List<String> paths){
if(root != null){
//StringBuffer是字符串变量,它的对象是可以灵活扩充和修改的
StringBuffer pathSB = new StringBuffer(path);
//Integer.toString(int par1,int par2)
//par1表示要转成字符串的数字,par2表示要转成的进制表示
pathSB.append(Integer.toString(root.val));
if(root.right == null && root.left == null){//这里表示找到叶子节点了
paths.add(pathSB.toString());//toString是个方法,记得加()
}else{
//Java中的append( )方法其实是创建了一个新的数组
//扩大了长度,将需要添加的字符串给复制到这个新的数组中
//字符串拼接,输出结果要的答案
pathSB.append("->");
dfs(root.right,pathSB.toString(),paths);
dfs(root.left,pathSB.toString(),paths);
}
}
}
}
时间复杂度:O(N2)
空间复杂度:O(N2)
广度优先搜索
可以套用二叉树的广度优先搜索(层序遍历)模板,加上上面DFS的思路
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
//广度优先搜索
List<String> paths = new ArrayList<String>();
if(root == null) return paths;
Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
Queue<String> pathQueue = new LinkedList<String>();
nodeQueue.offer(root);
pathQueue.offer(Integer.toString(root.val));
while(!nodeQueue.isEmpty()){
TreeNode node = nodeQueue.poll();
String path = pathQueue.poll();
//报了超时异常,检查发现以下的所有node,都被写成了root
if(node.left == null && node.right == null){
paths.add(path);
}else{
if(node.left != null){
nodeQueue.offer(node.left);
//Line 38: error: cannot find symbol
//toSting后面忘了加括号,报bug了
pathQueue.offer(new StringBuffer(path).append("->").append(node.left.val).toString());
}
if(node.right != null){
nodeQueue.offer(node.right);
pathQueue.offer(new StringBuffer(path).append("->").append(node.right.val).toString());
}
}
}
return paths;
}
}
时间复杂度:O(N2)
空间复杂度:O(N2)