951. Flip Equivalent Binary Trees

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 equivelent or false otherwise.

 

Example 1:

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

Example 2:

Input: root1 = [], root2 = []
Output: true

Example 3:

Input: root1 = [], root2 = [1]
Output: false

Example 4:

Input: root1 = [0,null,1], root2 = []
Output: false

Example 5:

Input: root1 = [0,null,1], root2 = [0,1]
Output: true

 

Constraints:

  • The number of nodes in each tree is in the range [0, 100].
  • Each tree will have unique node values in the range [0, 99].

Rust Solution

struct Solution;
use rustgym_util::*;

trait FlipEq {
    fn flip_eq(root1: &TreeLink, root2: &TreeLink) -> bool;
}

impl FlipEq for TreeLink {
    fn flip_eq(root1: &TreeLink, root2: &TreeLink) -> bool {
        if let (Some(node1), Some(node2)) = (root1, root2) {
            let val1 = node1.borrow().val;
            let val2 = node2.borrow().val;
            let left1 = &node1.borrow().left;
            let right1 = &node1.borrow().right;
            let left2 = &node2.borrow().left;
            let right2 = &node2.borrow().right;
            val1 == val2
                && (Self::flip_eq(left1, left2) && Self::flip_eq(right1, right2)
                    || Self::flip_eq(left1, right2) && Self::flip_eq(right1, left2))
        } else {
            root1 == root2
        }
    }
}

impl Solution {
    fn flip_equiv(root1: TreeLink, root2: TreeLink) -> bool {
        TreeLink::flip_eq(&root1, &root2)
    }
}

#[test]
fn test() {
    let root1 = tree!(
        1,
        tree!(2, tree!(4), tree!(5, tree!(7), tree!(8))),
        tree!(3, tree!(6), None)
    );
    let root2 = tree!(
        1,
        tree!(3, None, tree!(6)),
        tree!(2, tree!(4), tree!(5, tree!(8), tree!(7)))
    );
    let res = true;
    assert_eq!(Solution::flip_equiv(root1, root2), res);
    let root1 = tree!(0, tree!(3), tree!(1, None, tree!(2)));
    let root2 = tree!(0, tree!(3, tree!(2), None), tree!(1));
    let res = false;
    assert_eq!(Solution::flip_equiv(root1, root2), res);
}

Having problems with this solution? Click here to submit an issue on github.