Skip to content

Commit 8e907be

Browse files
committed
solve #145
1 parent 31acb2f commit 8e907be

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,4 @@ mod n0139_word_break;
139139
mod n0140_word_break_ii;
140140
mod n0143_reorder_list;
141141
mod n0144_binary_tree_preorder_traversal;
142+
mod n0145_binary_tree_postorder_traversal;
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* [145] Binary Tree Postorder Traversal
3+
*
4+
* Given a binary tree, return the postorder traversal of its nodes' values.
5+
*
6+
* Example:
7+
*
8+
*
9+
* Input: [1,null,2,3]
10+
* 1
11+
* \
12+
* 2
13+
* /
14+
* 3
15+
*
16+
* Output: [3,2,1]
17+
*
18+
*
19+
* Follow up: Recursive solution is trivial, could you do it iteratively?
20+
*
21+
*/
22+
pub struct Solution {}
23+
use super::util::tree::{TreeNode, to_tree};
24+
25+
// submission codes start here
26+
27+
use std::rc::Rc;
28+
use std::cell::RefCell;
29+
impl Solution {
30+
pub fn postorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
31+
let mut res = Vec::new();
32+
Solution::helper(root, &mut res);
33+
res
34+
}
35+
36+
fn helper(root: Option<Rc<RefCell<TreeNode>>>, vec: &mut Vec<i32>) {
37+
if let Some(node) = root {
38+
Solution::helper(node.borrow().left.clone(), vec);
39+
Solution::helper(node.borrow().right.clone(), vec);
40+
vec.push(node.borrow().val);
41+
}
42+
}
43+
}
44+
45+
// submission codes end
46+
47+
#[cfg(test)]
48+
mod tests {
49+
use super::*;
50+
51+
#[test]
52+
fn test_145() {
53+
assert_eq!(Solution::postorder_traversal(tree![1,null,2,3]), vec![3,2,1]);
54+
}
55+
}

0 commit comments

Comments
 (0)