*LeetCode-Binary Tree Paths
881 ワード
いくつかのcorner caseは、例えば1つのノード、例えばノードがないroot自身はpathとは言えないからです.
root+->を使うのは->rootより便利です
root+->を使うのは->rootより便利です
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<String> ();
if ( root == null )
return list;
helper ( list, "", root);
return list;
}
public void helper ( List<String> list, String str, TreeNode cur ){
if ( cur.left == null && cur.right == null ){
str += Integer.toString( cur.val );
list.add ( str );
return;
}
str = str + Integer.toString( cur.val ) + "->";
if ( cur.left != null )
helper ( list, str, cur.left );
if ( cur.right != null )
helper ( list, str, cur.right );
}
}