---------------257. 二叉树的所有路径 题目链接-------------------
时间复杂度O(N)
空间复杂度O(N)
/**
* 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 {
List<String> result = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
helper(root,"");
return result;
}
public void helper(TreeNode root, String s){
// 前序 中左右
if(root == null) return;
if(root.left == null && root.right == null){
result.add(s + root.val);
}
String temp = s + root.val + "->";
helper(root.left,temp);
helper(root.right,temp);
}
}
StringBulider
深度优先遍历 添加了StringBulider
替代字符串拼接提升效率
toString()
转化为String
.append()
添加元素
时间复杂度O(N)
空间复杂度O(N)
/**
* 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 {
List<String> result = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
helper(root,"");
return result;
}
public void helper(TreeNode root, String s){
// 前序 中左右 使用StringBuilder提升效率
// 停止条件
if(root == null) return;
if(root.left == null && root.right == null){ // 如果遍历到叶子节点,那么就在result中添加该路径(该路径就是前面得到的s+当前值)
result.add(new StringBuilder(s).append(root.val).toString());
return;
}
String temp = new StringBuilder(s).append(root.val).append("->").toString(); // 中 当前路径 s 加上当前节点值和箭头 "->" 的组合
helper(root.left, temp); // 左
helper(root.right, temp); // 右
}
}