LeetCode 257Binary Tree Paths
来源:互联网 发布:别人的生活 知乎 编辑:程序博客网 时间:2024/05/22 04:51
/**
* 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> list = new ArrayList<>();
if(root == null){
return list;
}
StringBuilder sb = new StringBuilder();
rec(list,root,sb);
return list;
}
public void rec(List<String> list,TreeNode root,StringBuilder sb){
if(root.left == null&&root.right == null){ //如果root没有左右子节点了,直接在sb.append()
sb.append(root.val);
list.add(sb.toString());
return ;
}
// root至少有一个节点
sb.append(root.val);
sb.append("->");
int orilen = sb.length();// 记住最开始的root到当前的root的距离。
if(root.left!=null) rec(list,root.left,sb);
sb.setLength(orilen);
if(root.right!=null) rec(list,root.right,sb);
}
}
* 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> list = new ArrayList<>();
if(root == null){
return list;
}
StringBuilder sb = new StringBuilder();
rec(list,root,sb);
return list;
}
public void rec(List<String> list,TreeNode root,StringBuilder sb){
if(root.left == null&&root.right == null){ //如果root没有左右子节点了,直接在sb.append()
sb.append(root.val);
list.add(sb.toString());
return ;
}
// root至少有一个节点
sb.append(root.val);
sb.append("->");
int orilen = sb.length();// 记住最开始的root到当前的root的距离。
if(root.left!=null) rec(list,root.left,sb);
sb.setLength(orilen);
if(root.right!=null) rec(list,root.right,sb);
}
}
0 0
- leetcode 257: Binary Tree Paths
- leetCode #257 Binary Tree Paths
- LeetCode(257)Binary Tree Paths
- [leetcode 257]Binary Tree Paths
- leetcode[257] Binary Tree Paths
- LeetCode 257: Binary Tree Paths
- leetcode 257 : Binary Tree Paths
- 【LEETCODE】257-Binary Tree Paths
- [leetcode 257] Binary Tree Paths
- LeetCode 257 Binary Tree Paths
- LeetCode 257:Binary Tree Paths
- LeetCode 257:Binary Tree Paths
- leetcode 257:Binary Tree Paths
- leetcode-257-Binary Tree Paths
- LeetCode 257Binary Tree Paths
- LeetCode 257 Binary Tree Paths
- leetcode 257 Binary Tree Paths
- LeetCode-257:Binary Tree Paths
- spring security简单实例
- Android中自定义Dialog布局的两种方式比较
- 【BZOJ3687】简单题【bitset】
- Java 语言基础(一)
- 正则表达式:
- LeetCode 257Binary Tree Paths
- leedCode 334 Increasing Triplet Subsequence
- ps双11模板制作
- 【bzoj4421】【cerc2015】【Digit Division】
- 正则表达式----search
- 删除多级目录下的一类文件
- 大数的加法,减法,乘法
- Spring JDBC的CRUD方法详解
- Android开发60条技术经验总结