3.30 以为自己做不出来呢
没想到居然做出来了
还是利用递归的思想。
虽然做题慢了点,但是似乎找到那么一些感觉了呢。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
public static List<String> binaryTreePaths(TreeNode root){
List<String> s = new ArrayList<String>();
if(root == null){
return s;
}
if(root.left == null && root.right == null){
s.add(String.valueOf(root.val));
}
if(root.left != null){
List<String> h = binaryTreePaths(root.left);
for(int i = 0; i<h.size();i++){
String tmp = String.valueOf(root.val) + "->";
s.add(tmp + h.get(i));
}
}
if(root.right != null){
List<String> h = binaryTreePaths(root.right);
for(int i = 0; i<h.size();i++){
String tmp = String.valueOf(root.val) + "->";
s.add(tmp + h.get(i));
}
}
return s;
}
}
本文介绍了一种使用递归方法来寻找二叉树中所有从根节点到叶子节点的路径的方法。通过递归遍历左子树和右子树,并记录下路径,最终实现了算法的目标。
3588

被折叠的 条评论
为什么被折叠?



