题解|#判断t1树中是否有与t2树完全相同的子树#|Rust
判断t1树中是否有与t2树完全相同的子树
https://www.nowcoder.com/practice/4eaccec5ee8f4fe8a4309463b807a542
/** * #[derive(PartialEq, Eq, Debug, Clone)] * pub struct TreeNode { * pub val: i32, * pub left: Option<Box<TreeNode>>, * pub right: Option<Box<TreeNode>>, * } * * impl TreeNode { * #[inline] * fn new(val: i32) -> Self { * TreeNode { * val: val, * left: None, * right: None, * } * } * } */ struct Solution{ } impl Solution { fn new() -> Self { Solution{} } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root1 TreeNode类 * @param root2 TreeNode类 * @return bool布尔型 */ pub fn isContains(&self, root1: Option<Box<TreeNode>>, root2: Option<Box<TreeNode>>) -> bool { if root1.is_none() && root2.is_none() { return true; } if root1.is_none() || root2.is_none() { return false; } return Solution::dfs(self, Solution::find(self, root1, root2.as_ref().unwrap().val), root2); } fn find(&self, mut tree1: Option<Box<TreeNode>>, val: i32) -> Option<Box<TreeNode>> { if tree1.is_none() { return None } if tree1.as_ref().unwrap().val == val { return tree1; } let mut ans = Solution::find(self, tree1.as_mut().unwrap().left.take(), val); if ans.is_none() { ans = Solution::find(self, tree1.as_mut().unwrap().right.take(), val); } return ans; } fn dfs(&self, mut tree1: Option<Box<TreeNode>>, mut tree2: Option<Box<TreeNode>>) -> bool { if tree1.is_none() && tree2.is_none() { return true; } if tree1.is_none() || tree2.is_none() { return false; } if tree1.as_ref().unwrap().val != tree2.as_ref().unwrap().val { return false; } return Solution::dfs(self, tree1.as_mut().unwrap().left.take(), tree2.as_mut().unwrap().left.take()) && Solution::dfs(self, tree1.as_mut().unwrap().right.take(), tree2.as_mut().unwrap().right.take()); } }