# LeetCode: Flip Binary Tree To Match Preorder Traversal Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**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} root11 * @param {number[]} voyage12 * @return {number[]}13 */14var flipMatchVoyage = function (root, voyage) {15  const res = []16  let pos = 017
18  const traverse = node => {19    if (node === null) {20      return true21    }22    if (node.val !== voyage[pos++]) {23      return false24    }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}```

leetcode

tree

dfs

## Next Post

LeetCode: Stamping The Sequence

Mar 31, 2021

Search Posts