rust
复制代码
// [1,2,3] [1,2,3] true
// [1,2] [1,null,2] false
// [1,2,1] [1,1,2] false
use std::rc::Rc;
use std::cell::RefCell;
#[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
}
}
}
// 递归解法
pub fn is_same_tree(p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> bool {
match (p, q) {
(Some(p_node), Some(q_node)) => {
let p_borrow = p_node.borrow();
let q_borrow = q_node.borrow();
p_borrow.val == q_borrow.val &&
is_same_tree(p_borrow.left.clone(), q_borrow.left.clone()) &&
is_same_tree(p_borrow.right.clone(), q_borrow.right.clone())
}
(None, None) => true,
_ => false,
}
}
// 迭代解法
pub fn is_same_tree2(p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> bool {
let mut stack = vec![(p, q)];
while let Some((p, q)) = stack.pop() {
match (p, q) {
(Some(p_node), Some(q_node)) => {
let p_borrow = p_node.borrow();
let q_borrow = q_node.borrow();
if p_borrow.val != q_borrow.val {
return false;
}
stack.push((p_borrow.left.clone(), q_borrow.left.clone()));
stack.push((p_borrow.right.clone(), q_borrow.right.clone()));
}
(None, None) => continue,
_ => return false,
}
}
true
}
fn main() {
//根据[1,2,3] [1,2,3] true编写测试用例
let tree1 = Some(Rc::new(RefCell::new(TreeNode {
val:1,
left:Some(Rc::new(RefCell::new(TreeNode {
val:2,
left:None,
right:None,
}))),
right:Some(Rc::new(RefCell::new(TreeNode {
val:3,
left:None,
right:None,
}))),
})));
let tree2 = Some(Rc::new(RefCell::new(TreeNode {
val:1,
left:Some(Rc::new(RefCell::new(TreeNode {
val:2,
left:None,
right:None,
}))),
right:Some(Rc::new(RefCell::new(TreeNode {
val:3,
left:None,
right:None,
}))),
})));
assert_eq!(is_same_tree(tree1.clone(), tree2.clone()), true);
assert_eq!(is_same_tree2(tree1.clone(), tree2.clone()), true);
}