- Binary Tree Paths
打印所有根到叶子的路径
100% test cases passedTotal runtime 320 ms
Your submission beats 39.80% Submissions!
/**
* 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 List<String> binaryTreePaths(TreeNode root) {
List<String> ret = new ArrayList<>();
if(root==null)
return ret;
List<String> lret = binaryTreePaths(root.left);
List<String> rret = binaryTreePaths(root.right);
for(String path : lret){
ret.add(root.val+"->"+path);
}
for(String path : rret){
ret.add(root.val+"->"+path);
}
if(ret.size()==0)
ret.add(""+root.val);
return ret;
}
}
网友评论