LeetCode 872. Leaf-Similar Trees

Problem Statement


// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
fn dfs(root: Option<Rc<RefCell<TreeNode>>>, v: &mut Vec<i32>) {
if let Some(node) = root {
if !node.borrow().left.is_none() {
Self::dfs(node.borrow().left.clone(), v);
}
if node.borrow().left.is_none() && node.borrow().right.is_none() {
v.push(node.borrow().val);
}
if !node.borrow().right.is_none() {
Self::dfs(node.borrow().right.clone(), v);
}
}
}
pub fn leaf_similar(root1: Option<Rc<RefCell<TreeNode>>>, root2: Option<Rc<RefCell<TreeNode>>>) -> bool {
let (mut v1, mut v2) = (vec![], vec![]);
Self::dfs(root1, &mut v1);
Self::dfs(root2, &mut v2);
return v1 == v2;
}
}