Flip The Tree!!!!

Fun problem: https://leetcode.com/problems/flip-equivalent-binary-trees/description/

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.
Flipped Trees Diagram

Note:
  1. Each tree will have at most 100 nodes.
  2. Each value in each tree will be a unique integer in the range [0, 99].
It is actually pretty simple (recursively), 3-lines, cheers, ACC.


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));
}
}

Comments

  1. Great minds think alike )):

    class 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)

    ReplyDelete
  2. Replies
    1. haha, 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

Post a Comment

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Golang vs. C#: performance characteristics (simple case study)

Advent of Code - Day 7, 2024: Backtracking and Eval