Open Zheaoli opened 1 year ago
/*
* @lc app=leetcode id=111 lang=typescript
*
* [111] Minimum Depth of Binary Tree
*/
// @lc code=start
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function minDepth(root: TreeNode | null): number {
let min = 0;
const walk = (node, depth = 0) => {
if (!node.left && !node.right) {
if (min === 0) {
min = depth + 1;
} else {
min = Math.min(min, depth + 1);
}
return;
}
node.left && walk(node.left, depth + 1);
node.right && walk(node.right, depth + 1);
}
root && walk(root);
return min;
}
// @lc code=end
微信id: 弘树 来自 vscode 插件
2022-10-16