Flip The Tree!!!!
Fun problem: https://leetcode.com/problems/flip-equivalent-binary-trees/description/
public class Solution
{
public bool FlipEquiv(TreeNode root1, TreeNode root2)
{
if (root1 == null && root2 == null) return true;
if (root1 == null || root2 == null || root1.val != root2.val) return false;
return (FlipEquiv(root1.left, root2.left) && FlipEquiv(root1.right, root2.right)) ||
(FlipEquiv(root1.left, root2.right) && FlipEquiv(root1.right, root2.left));
}
}
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.
Write a function that determines whether two binary trees are flip equivalent. The trees are given by root nodes
root1
and root2
.
Example 1:
Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7] Output: true Explanation: We flipped at nodes with values 1, 3, and 5.
Note:
- Each tree will have at most
100
nodes. - Each value in each tree will be a unique integer in the range
[0, 99]
.
public class Solution
{
public bool FlipEquiv(TreeNode root1, TreeNode root2)
{
if (root1 == null && root2 == null) return true;
if (root1 == null || root2 == null || root1.val != root2.val) return false;
return (FlipEquiv(root1.left, root2.left) && FlipEquiv(root1.right, root2.right)) ||
(FlipEquiv(root1.left, root2.right) && FlipEquiv(root1.right, root2.left));
}
}
Great minds think alike )):
ReplyDeleteclass Solution:
def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
if root1 is root2:
return True
if root1 is None or root2 is None or root1.val != root2.val:
return False
return (
self.flipEquiv(root1.left, root2.left)
and self.flipEquiv(root1.right, root2.right)
) or (
self.flipEquiv(root1.left, root2.right)
and self.flipEquiv(root1.right, root2.left)
)
https://gist.github.com/ttsugriy/2e241cc61a2c05224b52c7dc9c139e45
Interestingly Python keeps beating C# in CPU and memory usage :) (36ms and 6.5MB of RAM)
I will learn Python 🐍
ReplyDeletehaha, I prefer strongly typed languages but Python is definitely a language of choice for ML these days. It's also a great choice for interviews because it's pretty much pseudocode :)
Delete