257. Binary Tree Paths
题目描述
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1-
>
2-
>
5", "1-
>
3"]
解题方法
判別root->left == null
root->right == null 再加以遞迴
public List<String> binaryTreePaths(TreeNode root){
List<String> list = new ArrayList<>();
if(root == null){ return list;}
DFS(root, list, "");
return list;
}
private void DFS(TreeNode root, List<String> list, String str){
if(root == null){ return;}
//leaf node
if(root.left == null && root.right == null){
str += root.val;
list.add(str);
return;
}
if(root.left != null){
DFS(root.left, list, str + root.val + "->");
}
if(root.right != null){
DFS(root.right, list, str + root.val + "->");
}
}