Day 36 - LeetCode 257. Binary Tree Paths

LeetCode 111. Minimum Depth of Binary Tree

題目

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到leaf的路徑,例如圖中的二元樹,
有兩條路徑["1->2->5", "1->3"]

想法

跟LeetCode 111. 差不多,已經找出過深度,就把它記錄起來,然後放到陣列裡。
DFS:深度優先搜尋,也就是一條路直直走完

詳細參閱

https://discuss.leetcode.com/topic/79347/javascript-recursive-o-n
https://discuss.leetcode.com/topic/77315/javascript-dfs-solution-need-some-review


Code

/**
 * 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) {
    if (!root) {
        return [];
    }
    let list = [];
    
    find(root, '');
    
    return list;

    function find(node, str) {
        //當都找不子節點的時候存入陣列
        if (!node.left && !node.right) {
            list.push(str + node.val);
        } else {
            if (node.left) {
                find(node.left, str + node.val + '->');
            }
            if (node.right) {
                find(node.right, str + node.val + '->');
            }
        }    
    }
};
/**
 * 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) {
    if (!root) {
        return [];
    }  
    if (!root.left && !root.right) {
        return [String(root.val)];
    }
    
    let list = binaryTreePaths(root.left)
            .concat(binaryTreePaths(root.right));
    return list.map(path => `${root.val}->${path}`);
}

Run

留言