Created
August 23, 2023 05:44
-
-
Save trvswgnr/f15189240541baf3dd37a8c2eca00cd3 to your computer and use it in GitHub Desktop.
invert binary tree neg operator crab
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
// create a new binary tree | |
let mut root = TreeNode::new(1); | |
let left_child = TreeNode::new(2); | |
let right_child = TreeNode::new(3); | |
root.set_left(left_child); | |
root.set_right(right_child); | |
// invert the binary tree | |
let inverted_root = -root; | |
// check the values of the inverted tree's children | |
assert_eq!(inverted_root.get_left().val, 3); | |
assert_eq!(inverted_root.get_right().val, 2); | |
println!("tr4vvy r00lz"); | |
} | |
use std::ptr; | |
#[derive(Clone)] | |
pub struct TreeNode { | |
pub val: i32, | |
pub left: *mut TreeNode, | |
pub right: *mut TreeNode, | |
} | |
impl TreeNode { | |
pub fn new(val: i32) -> Self { | |
TreeNode { | |
val, | |
left: ptr::null_mut(), | |
right: ptr::null_mut(), | |
} | |
} | |
pub fn set_left(&mut self, node: Self) { | |
self.left = Box::into_raw(Box::new(node)); | |
} | |
pub fn set_right(&mut self, node: Self) { | |
self.right = Box::into_raw(Box::new(node)); | |
} | |
pub fn get_left(&self) -> Self { | |
unsafe { (*self.left).clone() } | |
} | |
pub fn get_right(&self) -> Self { | |
unsafe { (*self.right).clone() } | |
} | |
} | |
impl std::ops::Neg for TreeNode { | |
type Output = Self; | |
fn neg(self) -> Self::Output { | |
unsafe { | |
let left = if !self.left.is_null() { | |
let left_box = Box::from_raw(self.left); | |
let inverted_left = -(*left_box); | |
Box::into_raw(Box::new(inverted_left)) | |
} else { | |
ptr::null_mut() | |
}; | |
let right = if !self.right.is_null() { | |
let right_box = Box::from_raw(self.right); | |
let inverted_right = -(*right_box); | |
Box::into_raw(Box::new(inverted_right)) | |
} else { | |
ptr::null_mut() | |
}; | |
Self::Output { | |
val: self.val, | |
left: right, | |
right: left, | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment