|
@@ -0,0 +1,38 @@
|
|
|
+use std::rc::Rc;
|
|
|
+use std::cell::RefCell;
|
|
|
+use crate::solutions::TreeNode;
|
|
|
+struct Solution;
|
|
|
+impl Solution {
|
|
|
+ pub fn postorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
|
|
|
+ let mut res = vec![];
|
|
|
+
|
|
|
+ Solution::helper(root, &mut res);
|
|
|
+ res
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ fn helper(root: Option<Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
|
|
|
+ if let Some(node) = root {
|
|
|
+ let val = node.borrow().val;
|
|
|
+
|
|
|
+ Solution::helper(node.borrow().left.clone(), res);
|
|
|
+ Solution::helper(node.borrow().right.clone(), res);
|
|
|
+ res.push(val);
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+#[cfg(test)]
|
|
|
+mod tests {
|
|
|
+ use crate::solutions::vec_to_tree;
|
|
|
+ use super::*;
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn test_postorder_traversal() {
|
|
|
+ let nums = vec![Some(1), None, Some(2), None, None, Some(3)];
|
|
|
+ let root = vec_to_tree(nums);
|
|
|
+ let res = Solution::postorder_traversal(root);
|
|
|
+ assert_eq!(res, vec![3,2,1]);
|
|
|
+ }
|
|
|
+
|
|
|
+}
|