951. Flip Equivalent Binary Trees
Difficulty: Medium
Topics: Tree, Depth-First Search, Binary Tree
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 root1 and root2, return true if the two trees are flip equivalent or false otherwise.
Example 1:
Example 2:
Example 3:
Constraints:
Solution:
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.
Base Cases:
Recursive Case:
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) { ... ... ... /** * go to ./solution.php */ } // 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) ?>
TreeNode Class: The TreeNode class represents a node in the binary tree, with a constructor to initialize the node's value, left child, and right child.
flipEquiv Function:
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of . Flip Equivalent Binary Trees. For more information, please follow other related articles on the PHP Chinese website!