951. Flip Equivalent Binary Trees #743
-
Topics: For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees. A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations. Given the roots of two binary trees Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a recursive depth-first search (DFS). The idea is that two trees are flip equivalent if their root values are the same, and the subtrees are either the same (without any flips) or they become the same after flipping the left and right children at some nodes. Plan:
Let's implement this solution in PHP: 951. Flip Equivalent Binary Trees <?php
// Definition for a binary tree node.
class TreeNode {
public $val;
public $left;
public $right;
function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
/**
* @param TreeNode $root1
* @param TreeNode $root2
* @return Boolean
*/
function flipEquiv($root1, $root2) {
// If both nodes are null, they are equivalent
if ($root1 === null && $root2 === null) {
return true;
}
// If one of the nodes is null or the values don't match, they are not equivalent
if ($root1 === null || $root2 === null || $root1->val !== $root2->val) {
return false;
}
// Check both possibilities:
// 1. No flip: left with left and right with right
// 2. Flip: left with right and right with left
return (flipEquiv($root1->left, $root2->left) && flipEquiv($root1->right, $root2->right)) ||
(flipEquiv($root1->left, $root2->right) && flipEquiv($root1->right, $root2->left));
}
// Example usage:
$root1 = new TreeNode(1,
new TreeNode(2, new TreeNode(4), new TreeNode(5, new TreeNode(7), new TreeNode(8))),
new TreeNode(3, new TreeNode(6), null)
);
$root2 = new TreeNode(1,
new TreeNode(3, null, new TreeNode(6)),
new TreeNode(2, new TreeNode(4), new TreeNode(5, new TreeNode(8), new TreeNode(7)))
);
var_dump(flipEquiv($root1, $root2)); // Output: bool(true)
?> Explanation:
Time Complexity:
Space Complexity:
|
Beta Was this translation helpful? Give feedback.
We can use a recursive depth-first search (DFS). The idea is that two trees are flip equivalent if their root values are the same, and the subtrees are either the same (without any flips) or they become the same after flipping the left and right children at some nodes.
Plan:
Base Cases:
root1
androot2
arenull
, they are trivially flip equivalent.null
, they can't be equivalent.root1
androot2
are different, they can't be equivalent.Recursive Case:
root1
is flip equivalent to the left subtree ofroot2
, and the right subtree ofroot1
is flip equivalent to the right subtre…