forked from aylei/leetcode-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp0094_binary_tree_inorder_traversal.rs
103 lines (97 loc) · 2.56 KB
/
p0094_binary_tree_inorder_traversal.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* [94] Binary Tree Inorder Traversal
*
* Given the root of a binary tree, return the inorder traversal of its nodes' values.
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" style="width: 202px; height: 324px;" />
* Input: root = [1,null,2,3]
* Output: [1,3,2]
*
* Example 2:
*
* Input: root = []
* Output: []
*
* Example 3:
*
* Input: root = [1]
* Output: [1]
*
* Example 4:
* <img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/inorder_5.jpg" style="width: 202px; height: 202px;" />
* Input: root = [1,2]
* Output: [2,1]
*
* Example 5:
* <img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/inorder_4.jpg" style="width: 202px; height: 202px;" />
* Input: root = [1,null,2]
* Output: [1,2]
*
*
* Constraints:
*
* The number of nodes in the tree is in the range [0, 100].
* -100 <= Node.val <= 100
*
*
* Follow up:
* Recursive solution is trivial, could you do it iteratively?
*
*
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
// problem: https://leetcode.com/problems/binary-tree-inorder-traversal/
// discuss: https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
// 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
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
match(root) {
None=>{vec![]},
Some(node)=>{
let mut left_vec = Self::inorder_traversal(node.borrow_mut().left.take());
let mut right_vec = Self::inorder_traversal(node.borrow_mut().right.take());
left_vec.extend(vec![node.borrow().val]);
left_vec.extend(right_vec);
left_vec
}
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_94() {
assert_eq!(
Solution::inorder_traversal(tree![1, null, 2, 3]),
vec![1, 3, 2]
);
assert_eq!(
Solution::inorder_traversal(tree![1, 2, 3, 4, 5, 6, 7]),
vec![4, 2, 5, 1, 6, 3, 7]
);
}
}