LeetCode: Flip Binary Tree To Match Preorder Traversal 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 * @param {number[]} voyage
12 * @return {number[]}
13 */
14var flipMatchVoyage = function (root, voyage) {
15 const res = []
16 let pos = 0
17
18 const traverse = node => {
19 if (node === null) {
20 return true
21 }
22 if (node.val !== voyage[pos++]) {
23 return false
24 }
25 if (node.left !== null && node.left.val !== voyage[pos]) {
26 res.push(node.val)
27 return traverse(node.right) && traverse(node.left)
28 }
29 return traverse(node.left) && traverse(node.right)
30 }
31
32 return traverse(root) ? res : [-1]
33}

Comments

Loading comments...

Tags

leetcode

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: Stamping The Sequence

HoningJS

Search Posts