LeetCode: Binary Tree Cameras Solution

1/**
2 * Definition for a binary tree node.
3 * function TreeNode(val, left, right) {
4 * this.val = (val===undefined ? 0 : val)
5 * this.left = (left===undefined ? null : left)
6 * this.right = (right===undefined ? null : right)
7 * }
8 */
9/**
10 * @param {TreeNode} root
11 * @return {number}
12 */
13var minCameraCover = function (root) {
14 let res = 0
15 const covered = new Set()
16 covered.add(null)
17
18 const dfs = (node, parent) => {
19 if (node === null) return
20
21 dfs(node.left, node)
22 dfs(node.right, node)
23
24 if (
25 (parent === null && !covered.has(node)) ||
26 !covered.has(node.left) ||
27 !covered.has(node.right)
28 ) {
29 res++
30 covered.add(parent)
31 covered.add(node)
32 covered.add(node.left)
33 covered.add(node.right)
34 }
35 }
36
37 dfs(root, null)
38
39 return res
40}

Comments

Loading comments...

Tags

leetcode

dynamic programming

tree

dfs

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Longest String Chain

HoningJS

Search Posts