-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpseudo_palindromic_paths.rs
49 lines (40 loc) · 1.22 KB
/
pseudo_palindromic_paths.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use std::cell::RefCell;
use std::rc::Rc;
// 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 }
}
}
// 1457. Pseudo-Palindromic Paths in a Binary Tree, Easy
// https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/
impl Solution {
pub fn pseudo_palindromic_paths(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut ans = 0;
fn dfs(ans: &mut i32, node: Option<Rc<RefCell<TreeNode>>>, mut mask: i32) {
if node.is_none() {
return;
}
let node = node.as_ref().unwrap().borrow();
mask ^= 1 << (node.val - 1);
if node.left.is_none() && node.right.is_none() {
if mask == mask & -mask {
*ans += 1;
}
} else {
dfs(ans, node.left.clone(), mask);
dfs(ans, node.right.clone(), mask);
}
}
dfs(&mut ans, root, 0);
ans
}
}
struct Solution {}