|
| 1 | +/** |
| 2 | + * 951. Flip Equivalent Binary Trees |
| 3 | + * https://leetcode.com/problems/flip-equivalent-binary-trees/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * For a binary tree T, we can define a flip operation as follows: choose any node, and swap the |
| 7 | + * left and right child subtrees. |
| 8 | + * |
| 9 | + * A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y |
| 10 | + * after some number of flip operations. |
| 11 | + * |
| 12 | + * Given the roots of two binary trees root1 and root2, return true if the two trees are flip |
| 13 | + * equivalent or false otherwise. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * Definition for a binary tree node. |
| 18 | + * function TreeNode(val, left, right) { |
| 19 | + * this.val = (val===undefined ? 0 : val) |
| 20 | + * this.left = (left===undefined ? null : left) |
| 21 | + * this.right = (right===undefined ? null : right) |
| 22 | + * } |
| 23 | + */ |
| 24 | +/** |
| 25 | + * @param {TreeNode} root1 |
| 26 | + * @param {TreeNode} root2 |
| 27 | + * @return {boolean} |
| 28 | + */ |
| 29 | +var flipEquiv = function(root1, root2) { |
| 30 | + return helper(root1, root2); |
| 31 | + |
| 32 | + function helper(node1, node2) { |
| 33 | + if (!node1 && !node2) return true; |
| 34 | + if (!node1 || !node2 || node1.val !== node2.val) return false; |
| 35 | + return (helper(node1.left, node2.left) && helper(node1.right, node2.right)) |
| 36 | + || (helper(node1.left, node2.right) && helper(node1.right, node2.left)); |
| 37 | + } |
| 38 | +}; |
0 commit comments