Skip to content

Commit a983f18

Browse files
committed
LC 1457. Pseudo-Palindromic Paths in a Binary Tree (Rust It)
1 parent bd4ccb5 commit a983f18

File tree

3 files changed

+101
-3
lines changed

3 files changed

+101
-3
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,7 @@ Solutions to LeetCode problems. The first column links to the problem in LeetCod
474474
| [1443. Minimum Time to Collect All Apples in a Tree][lc1443] | 🟠 Medium | [![python](res/py.png)][lc1443py] |
475475
| [1448. Count Good Nodes in Binary Tree][lc1448] | 🟠 Medium | [![python](res/py.png)][lc1448py] |
476476
| [1456. Maximum Number of Vowels in a Substring of Given Length][lc1456] | 🟠 Medium | [![rust](res/rs.png)][lc1456rs] |
477-
| [1457. Pseudo-Palindromic Paths in a Binary Tree][lc1457] | 🟠 Medium | [![python](res/py.png)][lc1457py] |
477+
| [1457. Pseudo-Palindromic Paths in a Binary Tree][lc1457] | 🟠 Medium | [![python](res/py.png)][lc1457py] [![rust](res/rs.png)][lc1457rs] |
478478
| [1461. Check If a String Contains All Binary Codes of Size K][lc1461] | 🟠 Medium | [![python](res/py.png)][lc1461py] |
479479
| [1462. Course Schedule IV][lc1462] | 🟠 Medium | [![python](res/py.png)][lc1462py] [![rust](res/rs.png)][lc1462rs] |
480480
| [1465. Maximum Area of a Piece of Cake After Cuts][lc1465] | 🟠 Medium | [![python](res/py.png)][lc1465py] |
@@ -1687,6 +1687,7 @@ Solutions to LeetCode problems. The first column links to the problem in LeetCod
16871687
[lc1456rs]: leetcode/maximum-number-of-vowels-in-a-substring-of-given-length.rs
16881688
[lc1457]: https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/
16891689
[lc1457py]: leetcode/pseudo-palindromic-paths-in-a-binary-tree.py
1690+
[lc1457rs]: leetcode/pseudo-palindromic-paths-in-a-binary-tree.rs
16901691
[lc1461]: https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/
16911692
[lc1461py]: leetcode/check-if-a-string-contains-all-binary-codes-of-size-k.py
16921693
[lc1462]: https://leetcode.com/problems/course-schedule-iv/

leetcode/pseudo-palindromic-paths-in-a-binary-tree.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@
2626
# call stack. h could be equal to n if each node had a single child.
2727
# The set uses O(1) because the values in the node can only be 1-9.
2828
#
29-
# Runtime: 1761 ms, faster than 20.88%
30-
# Memory Usage: 85.1 MB, less than 71.65%
29+
# Runtime: 351 ms, faster than 96%
30+
# Memory Usage: 43.46 MB, less than 98.67%
3131
class UsingSet:
3232
def pseudoPalindromicPaths(self, root: Optional[TreeNode]) -> int:
3333
# Root is guaranteed to not be null.
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// 1457. Pseudo-Palindromic Paths in a Binary Tree
2+
// 🟠 Medium
3+
//
4+
// https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/
5+
//
6+
// Tags: Bit Manipulation - Tree - Depth-First Search - Breadth-First Search - Binary Tree
7+
8+
use std::cell::RefCell;
9+
use std::rc::Rc;
10+
11+
// Definition for a binary tree node.
12+
#[derive(Debug, PartialEq, Eq)]
13+
pub struct TreeNode {
14+
pub val: i32,
15+
pub left: Option<Rc<RefCell<TreeNode>>>,
16+
pub right: Option<Rc<RefCell<TreeNode>>>,
17+
}
18+
19+
impl TreeNode {
20+
#[inline]
21+
pub fn new(val: i32) -> Self {
22+
TreeNode {
23+
val,
24+
left: None,
25+
right: None,
26+
}
27+
}
28+
}
29+
30+
struct Solution;
31+
impl Solution {
32+
/// Use DFS to explore each path in the tree from root to leaf, for each path, keep track of
33+
/// the values that we see, depending on the use that we want to give the value count, we might
34+
/// need to use a hashmap as a counter, in this case, we only need to know if we have seen each
35+
/// value an even or uneven number of times, for that we can use a set, value is present for
36+
/// uneven number of times, not present for 0 or even number of times. This solution uses the
37+
/// same logic as the Python solution but iterative DFS and a bitmask instead of recursive DFS
38+
/// and a hashset to make it a little different.
39+
///
40+
/// Time complexity: O(n) - We visit each value and do O(1) work for each.
41+
/// Space complexity: O(h) - The stack will grow to the height of the tree, which could be n.
42+
///
43+
/// Runtime 26 ms Beats 100%
44+
/// Memory 12.12 MB Beats 87.50%
45+
pub fn pseudo_palindromic_paths(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
46+
// A stack with the node and the values bitmask, we need at least 9 bits.
47+
let mut stack = vec![(root.unwrap(), 0u16)];
48+
let mut res = 0;
49+
while let Some((rc, mut seen)) = stack.pop() {
50+
let nr = rc.borrow();
51+
// Flip the bit for this value. Is guaranteed that 1 <= val <= 9.
52+
seen ^= 1 << nr.val;
53+
// Process the children
54+
match (nr.left.clone(), nr.right.clone()) {
55+
// No children, we are at a leaf, add 1 if the path values form a palindrome.
56+
(None, None) => {
57+
if seen.count_ones() < 2 {
58+
res += 1;
59+
}
60+
}
61+
(None, Some(child)) | (Some(child), None) => stack.push((child, seen)),
62+
(Some(left), Some(right)) => {
63+
stack.push((left, seen));
64+
stack.push((right, seen));
65+
}
66+
}
67+
}
68+
res
69+
}
70+
}
71+
72+
// Tests.
73+
fn main() {
74+
// let tests = [(vec![0], 0)];
75+
// println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len());
76+
// let mut success = 0;
77+
// for (i, t) in tests.iter().enumerate() {
78+
// let res = Solution::pseudo_palindromic_paths(t.0.clone());
79+
// if res == t.1 {
80+
// success += 1;
81+
// println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i);
82+
// } else {
83+
// println!(
84+
// "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m",
85+
// i, t.1, res
86+
// );
87+
// }
88+
// }
89+
// println!();
90+
// if success == tests.len() {
91+
// println!("\x1b[30;42m✔ All tests passed!\x1b[0m")
92+
// } else if success == 0 {
93+
// println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m")
94+
// } else {
95+
// println!("\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", tests.len() - success)
96+
// }
97+
}

0 commit comments

Comments
 (0)