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

[leetcode]問題解答と解説。104. Maximum Depth of Binary Tree [JavaScript]

[leetcode]問題解答と解説。104. Maximum Depth of Binary Tree [JavaScript]

皆さんleetCode好きですよね。私も好きです。
なかなかやる機会がないのですよね。
時間時間で。
私は私自身ある決意をして今臨んでいます。

では今日のleetCode。やったことをさらけ出します。

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

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

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

104. Maximum Depth of Binary Tree ルール

ざっくり翻訳

root二分木のを与えられて、その最大の深さを返します。

二分木の最大深度 は、ルートノードから最も遠いリーフノードまでの最長パスに沿ったノードの数です。

例1:
入力: root = [3,9,20、null、null、15,7]
出力: 3

例2:
入力: root = [1、null、2]
出力: 2

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

104. Maximum Depth of Binary Tree 問題ページ

104. Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree

my code is time over.

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

let t15 = new TreeNode(15)
let t7 = new TreeNode(7)
let t20 = new TreeNode(20, t15, t7)
let t9 = new TreeNode(9)
let root = new TreeNode(3, t9, t20)

function maxDepth(root) {
    let dep = 0
    let next = root
    while(next.val !== null){
        if(next.left !== null && next.right === null){
            next = next.left
            dep++
            continue;
        }
        if(next.right !== null && next.left === null) {
            next = next.right
            dep++
            continue;
        }
        if(next.left === null && next.right === null){
            break
        }
    }
    return dep
};

let result = maxDepth(root)

タイムオーバーで撃沈

104. Maximum Depth of Binary Tree。discussの中の一つの解答例

104. Maximum Depth of Binary Tree

var maxDepth = function(root) {
    if (!root) return 0;
    const queue = [root];
    let depth = 0;
    while (queue.length !== 0) {
        depth++;
        const len = queue.length;
        for (let i = 0; i < len; i++) {
            if (queue[i].left) queue.push(queue[i].left);
            if (queue[i].right) queue.push(queue[i].right);
        }
        queue.splice(0, len);
    }
    return depth;
};

渡ってきたrootをそのまま配列に入れて、数えられるようにする...
queue

104. Maximum Depth of Binary Treeをやってみて感想

再帰でできる方法はないか考えたが、引数を追加しないといけないので
それはできないと思ったが、Math.maxでできる。
なかなかこの答えに辿り着くことはなかっただろうと思う。TreeNode書いて実際に値動かしでゴニョゴニョして時間終了

カテゴリー leetCode