872. Leaf-Similar Trees

Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

 

Example 1:

Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
Output: true

Example 2:

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

Example 3:

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

Example 4:

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

Example 5:

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

 

Constraints:

  • The number of nodes in each tree will be in the range [1, 200].
  • Both of the given trees will have values in the range [0, 200].

Rust Solution

struct Solution;
use rustgym_util::*;

trait Leaves {
    fn preorder(&self, leaves: &mut Vec<i32>);
}

impl Leaves for TreeLink {
    fn preorder(&self, leaves: &mut Vec<i32>) {
        if let Some(node) = self {
            let node = node.borrow();
            let left = &node.left;
            let right = &node.right;
            if left.is_none() && right.is_none() {
                leaves.push(node.val);
            } else {
                left.preorder(leaves);
                right.preorder(leaves);
            }
        }
    }
}

impl Solution {
    fn leaf_similar(root1: TreeLink, root2: TreeLink) -> bool {
        let mut leaves1: Vec<i32> = vec![];
        let mut leaves2: Vec<i32> = vec![];
        root1.preorder(&mut leaves1);
        root2.preorder(&mut leaves2);
        leaves1 == leaves2
    }
}

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

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