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"]
感覺(jué)樹(shù)的題目不做著就很快忘了套路是怎么樣的,必須要經(jīng)常做潜腻。這道題一開(kāi)始不知道如何返回一個(gè)List of String, 看了答案發(fā)現(xiàn)了一些以前不知道的表達(dá)轩触。比如root.val + ""
就表示一個(gè)String,字符串內(nèi)容是root.val栏妖。 這道題用DFS做,遞歸的定義是:當(dāng)前路徑下托慨,如果該節(jié)點(diǎn)是葉節(jié)點(diǎn)拴泌,則將該路徑加入到res里省骂;如果該節(jié)點(diǎn)不是葉節(jié)點(diǎn),則繼續(xù)遍歷其左右節(jié)點(diǎn)局荚。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if (root == null){
return res;
}
helper(root, root.val + "");
return res;
}
private void helper(TreeNode root, String path){
if (root.left == null && root.right == null){
res.add(path);
}
if (root.left != null){
helper(root.left, path + "->" + root.left.val);
}
if (root.right != null){
helper(root.right, path + "->" + root.right.val);
}
}
}