森田賢二のleetCodeの使い方、解説、解答を毎日更新しているキャラクター

[leetcode]問題解答と解説。257. Binary Tree Paths [JavaScript]

[leetcode]問題解答と解説。257. Binary Tree Paths [JavaScript]

皆さんleetCode好きですよね。私も好きです。
なかなかやる機会がないのですよね。時間時間で。

私は私自身ある決意をして今臨んでいます。
モチベーションを保つためだけにやっています。
では今日のleetCode。
「257. Binary Tree Paths」の解決策と方法。自分がまず挑戦して
やったことをさらけ出します。

※下にある自分のコードは自分で設けた制限時間内に書けたところまです。
なので動く保証もなければ間違っている可能性もあるのでご了承くださいませ

これは
「私は年末までこれを続けたらどんなleetCoderになるか」のシリーズ。
実験的ブログ更新です。

森田賢二のleetCode
森田賢二のleetCode

257. Binary Tree Paths ルール

ざっくり和訳

root二分木の場合、すべてのルートからリーフへのパスを任意の順序で返します。

葉は子のないノードです

入力: root = [1,2,3、null、5]
出力: ["1-> 2-> 5"、 "1-> 3"]

入力:ルート= [1]
出力: ["1"]

制約
ツリー内のノードの数はの範囲内[1, 100]です。
-100 <= Node.val <= 100

257. Binary Tree Paths 問題ページ

257. Binary Tree Paths

257. Binary Tree Paths

my code is time over.

 class TreeNode {
      val
      left
      right
      constructor(val, left, right) {
          this.val = (val===undefined ? 0 : val)
          this.left = (left===undefined ? null : left)
          this.right = (right===undefined ? null : right)
      }
 }

function binaryTreePaths(root, result = []) {
    let node = root
    while(node?.val || null !== null){
        result.push(node.val, node.left?.val || null, node.right?.val || null)
        binaryTreePaths(node.left, result)
        binaryTreePaths(node.right, result)
    }
    return result
};

let rightRight = new TreeNode(5)
let right = new TreeNode(3, null, rightRight)
let left = new TreeNode(2)
let root = new TreeNode(1, left, right)

console.log(binaryTreePaths(root))

タイムオーバーで撃沈

257. Binary Tree Paths。discussの中の一つの解答例

数ある中からJavaScriptのもので、理解しやすい解説をピックアップしました。
discussから見ればさらにもっと違う方法で真似したくなるものがあるかもしれないですね
JavaScriptでfilterされている、discussはこちらから

257. Binary Tree Paths

 // If null return an empty array
    if (root === null) return [];
    // If no children return the nodes value itself as a string within an array
    else if (root.left === null && root.right === null) return [`${root.val}`];
    else {
        // For all child paths add the root to their head one by one.
        let left = binaryTreePaths(root.left).map(x => root.val + '->' + x);
        let right = binaryTreePaths(root.right).map(x => root.val + '->' + x);

        // return the array with the root value attached
        return [...left, ...right];
    }

257. Binary Tree Pathsをやってみて感想

カテゴリー leetCode