|
| 1 | +/** |
| 2 | + * 971. Flip Binary Tree To Match Preorder Traversal |
| 3 | + * https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given the root of a binary tree with n nodes, where each node is uniquely assigned a |
| 7 | + * value from 1 to n. You are also given a sequence of n values voyage, which is the desired |
| 8 | + * pre-order traversal of the binary tree. |
| 9 | + * |
| 10 | + * Any node in the binary tree can be flipped by swapping its left and right subtrees. For |
| 11 | + * example, flipping node 1 will have the following effect. |
| 12 | + * |
| 13 | + * Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage. |
| 14 | + * |
| 15 | + * Return a list of the values of all flipped nodes. You may return the answer in any order. |
| 16 | + * If it is impossible to flip the nodes in the tree to make the pre-order traversal match |
| 17 | + * voyage, return the list [-1]. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * Definition for a binary tree node. |
| 22 | + * function TreeNode(val, left, right) { |
| 23 | + * this.val = (val===undefined ? 0 : val) |
| 24 | + * this.left = (left===undefined ? null : left) |
| 25 | + * this.right = (right===undefined ? null : right) |
| 26 | + * } |
| 27 | + */ |
| 28 | +/** |
| 29 | + * @param {TreeNode} root |
| 30 | + * @param {number[]} voyage |
| 31 | + * @return {number[]} |
| 32 | + */ |
| 33 | +var flipMatchVoyage = function(root, voyage) { |
| 34 | + const flips = []; |
| 35 | + let index = 0; |
| 36 | + return traverse(root) ? flips : [-1]; |
| 37 | + |
| 38 | + function traverse(node) { |
| 39 | + if (!node) return true; |
| 40 | + if (node.val !== voyage[index++]) return false; |
| 41 | + |
| 42 | + if (!node.left) return traverse(node.right); |
| 43 | + if (node.left.val === voyage[index]) return traverse(node.left) && traverse(node.right); |
| 44 | + |
| 45 | + flips.push(node.val); |
| 46 | + [node.left, node.right] = [node.right, node.left]; |
| 47 | + return traverse(node.left) && traverse(node.right); |
| 48 | + } |
| 49 | +}; |
0 commit comments