ソースを参照

feat: binary_tree_preorder_traversal

Zhang Li 11 ヶ月 前
コミット
306cdce649

+ 38 - 0
src/solutions/binary_search/binary_tree_postorder_traversal.rs

@@ -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]);
+    }
+
+}

+ 38 - 0
src/solutions/binary_search/binary_tree_preorder_traversal.rs

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

+ 2 - 0
src/solutions/binary_search/mod.rs

@@ -5,3 +5,5 @@ mod sqrt;
 mod search_2d_matrix;
 mod search_in_rotated_sorted_array2;
 mod median_of_two_sorted_arrays;
+mod binary_tree_preorder_traversal;
+mod binary_tree_postorder_traversal;