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"]
这个使用递归来做是最合适的,从根节点开始,将每个经过的节点添加到路径里,并把路径传给子节点,直到没有子节点。

/**
 * 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;
};

你可能感兴趣的:(257. Binary Tree Paths)