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"]
這個(gè)使用遞歸來做是最合適的,從根節(jié)點(diǎn)開始丸边,將每個(gè)經(jīng)過的節(jié)點(diǎn)添加到路徑里卤橄,并把路徑傳給子節(jié)點(diǎn)拨扶,直到?jīng)]有子節(jié)點(diǎn)片仿。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function(root) {
var a = [];
if (!root) {
return a;
}
var path = "";
var help = function(root,path) {
if (!root.left&&!root.right) {
path = path + root.val;
a.push(path);
return;
}
path = path + root.val +"->";
if (root.right)
help(root.right,path);
if (root.left)
help(root.left,path);
}
help(root,path);
return a;
};