From 3305fea5ae2101e0ef2ae3b88c74a9e3733b13dd Mon Sep 17 00:00:00 2001 From: jackfiled Date: Thu, 8 Feb 2024 10:36:24 +0800 Subject: [PATCH] 20240208 Finished --- src/problem/mod.rs | 3 +- src/problem/p993_cousins_in_binary_tree.rs | 112 +++++++++++++++++++++ 2 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 src/problem/p993_cousins_in_binary_tree.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index f8a6f6d..39d2f8b 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -40,4 +40,5 @@ mod p1690_stone_game_vii; mod p292_nim_game; mod p1696_jump_game_vi; mod lcp30_magic_tower; -mod p2641_cousins_in_binary_tree_ii; \ No newline at end of file +mod p2641_cousins_in_binary_tree_ii; +mod p993_cousins_in_binary_tree; \ No newline at end of file diff --git a/src/problem/p993_cousins_in_binary_tree.rs b/src/problem/p993_cousins_in_binary_tree.rs new file mode 100644 index 0000000..97000cb --- /dev/null +++ b/src/problem/p993_cousins_in_binary_tree.rs @@ -0,0 +1,112 @@ +/** + * [993] Cousins in Binary Tree + */ +pub struct Solution {} + +use crate::util::tree::{TreeNode, to_tree}; + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; + +struct Tree { + root: Rc>, + x: i32, + x_height: usize, + x_parent: i32, + y: i32, + y_height: usize, + y_parent: i32 +} + +impl Tree { + fn new(root: Rc>, x: i32, y: i32) -> Tree { + return Tree { + root, + x, + x_height: 0, + x_parent: 0, + y, + y_height: 0, + y_parent: 0 + } + } + + fn dfs(&mut self, node: &Rc>, height: usize, parent: i32) { + let (mut x_find, mut y_find) = (false, false); + + if node.borrow().val == self.x { + self.x_height = height; + self.x_parent = parent; + + x_find = true; + } + + if node.borrow().val == self.y { + self.y_height = height; + self.y_parent = parent; + + y_find = true; + } + + if x_find && y_find { + return; + } + + if let Some(left) = &node.borrow().left { + self.dfs(left, height + 1, node.borrow().val); + } + + if let Some(right) = &node.borrow().right { + self.dfs(right, height + 1, node.borrow().val); + } + } +} + +impl Solution { + pub fn is_cousins(root: Option>>, x: i32, y: i32) -> bool { + let root = if let Some(r) = root { + r + } else { + return false; + }; + + let mut tree = Tree::new(Rc::clone(&root), x, y); + tree.dfs(&root, 0, -1); + + + tree.x_height == tree.y_height && tree.x_parent != tree.y_parent + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_993() { + assert!(!Solution::is_cousins(to_tree(vec![Some(1),Some(2),Some(3),Some(4)]), + 4, 3)); + } +}