Skip to content

Commit baeee41

Browse files
committed
Solve #226
1 parent abc4989 commit baeee41

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,3 +193,4 @@ mod n0223_rectangle_area;
193193
mod n0222_count_complete_tree_nodes;
194194
mod n0224_basic_calculator;
195195
mod n0225_implement_stack_using_queues;
196+
mod n0226_invert_binary_tree;

src/n0226_invert_binary_tree.rs

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* [226] Invert Binary Tree
3+
*
4+
* Invert a binary tree.
5+
*
6+
* Example:
7+
*
8+
* Input:
9+
*
10+
*
11+
* 4
12+
* / \
13+
* 2 7
14+
* / \ / \
15+
* 1 3 6 9
16+
*
17+
* Output:
18+
*
19+
*
20+
* 4
21+
* / \
22+
* 7 2
23+
* / \ / \
24+
* 9 6 3 1
25+
*
26+
* Trivia:<br />
27+
* This problem was inspired by <a href="https://twitter.com/mxcl/status/608682016205344768" target="_blank">this original tweet</a> by <a href="https://twitter.com/mxcl" target="_blank">Max Howell</a>:
28+
*
29+
* <blockquote>Google: 90% of our engineers use the software you wrote (Homebrew), but you can&rsquo;t invert a binary tree on a whiteboard so f*** off.</blockquote>
30+
*
31+
*/
32+
pub struct Solution {}
33+
use super::util::tree::{to_tree, TreeNode};
34+
35+
// submission codes start here
36+
37+
use std::cell::RefCell;
38+
use std::rc::Rc;
39+
impl Solution {
40+
pub fn invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
41+
if let Some(node) = root.clone() {
42+
Solution::invert_tree(node.borrow().right.clone());
43+
Solution::invert_tree(node.borrow().left.clone());
44+
let left = node.borrow().left.clone();
45+
let right = node.borrow().right.clone();
46+
node.borrow_mut().left = right;
47+
node.borrow_mut().right = left;
48+
}
49+
root
50+
}
51+
}
52+
53+
// submission codes end
54+
55+
#[cfg(test)]
56+
mod tests {
57+
use super::*;
58+
59+
#[test]
60+
fn test_226() {
61+
assert_eq!(Solution::invert_tree(tree![4,2,7,1,3,6,9]), tree![4,7,2,9,6,3,1]);
62+
}
63+
}

0 commit comments

Comments
 (0)