Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e8340e8

Browse files
author
guangsheng.li01
committed
Solved 0019
1 parent 73cc484 commit e8340e8

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
* [0019] binary-tree-inorder-traversal
3+
*/
4+
5+
pub struct Solution {}
6+
use super::utils::tree::TreeNode;
7+
8+
// solution impl starts here
9+
10+
// Definition for a binary tree node.
11+
// #[derive(Debug, PartialEq, Eq)]
12+
// pub struct TreeNode {
13+
// pub val: i32,
14+
// pub left: Option<Rc<RefCell<TreeNode>>>,
15+
// pub right: Option<Rc<RefCell<TreeNode>>>,
16+
// }
17+
//
18+
// impl TreeNode {
19+
// #[inline]
20+
// pub fn new(val: i32) -> Self {
21+
// TreeNode {
22+
// val,
23+
// left: None,
24+
// right: None
25+
// }
26+
// }
27+
// }
28+
use std::cell::RefCell;
29+
use std::rc::Rc;
30+
impl Solution {
31+
pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
32+
let mut res: Vec<i32> = Vec::new();
33+
let mut curr = root.clone();
34+
35+
while let Some(cur) = curr.clone() {
36+
let cur = cur.borrow();
37+
if cur.left.is_some() {
38+
let mut pre = cur.left.clone().unwrap();
39+
while pre.borrow().right.is_some() && pre.borrow().right != curr {
40+
let a = pre.borrow().right.clone().unwrap();
41+
pre = a;
42+
}
43+
if pre.borrow().right.is_none() {
44+
pre.borrow_mut().right = curr;
45+
curr = cur.left.clone();
46+
}
47+
if pre.borrow().right == curr {
48+
pre.borrow_mut().right = Option::None;
49+
res.push(cur.val);
50+
curr = cur.right.clone();
51+
}
52+
} else {
53+
res.push(cur.val);
54+
curr = cur.right.clone();
55+
}
56+
}
57+
58+
res
59+
}
60+
}
61+
// solution impl ends here
62+
63+
// solution tests starts here
64+
65+
#[cfg(test)]
66+
mod tests {
67+
use super::*;
68+
69+
#[test]
70+
fn test_case0() {
71+
assert_eq!(
72+
Solution::inorder_traversal(tree![1, null, 2, 3]),
73+
vec![1, 3, 2]
74+
);
75+
}
76+
}
77+
78+
// solution tests ends here

‎src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ mod a0001_two_sum;
88
mod a0004_median_of_two_sorted_arrays;
99
mod a0007_reverse_integer;
1010
mod a0009_palindrome_number;
11+
mod a0019_binary_tree_inorder_traversal;
1112
mod a0026_remove_duplicates_from_sorted_array;
1213
mod a0027_remove_element;
1314
mod a0035_search_insert_position;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /