|
| 1 | +/** |
| 2 | + * [257] Binary Tree Paths |
| 3 | + * |
| 4 | + * Given a binary tree, return all root-to-leaf paths. |
| 5 | + * |
| 6 | + * Note: A leaf is a node with no children. |
| 7 | + * |
| 8 | + * Example: |
| 9 | + * |
| 10 | + * |
| 11 | + * Input: |
| 12 | + * |
| 13 | + * 1 |
| 14 | + * / \ |
| 15 | + * 2 3 |
| 16 | + * \ |
| 17 | + * 5 |
| 18 | + * |
| 19 | + * Output: ["1->2->5", "1->3"] |
| 20 | + * |
| 21 | + * Explanation: All root-to-leaf paths are: 1->2->5, 1->3 |
| 22 | + * |
| 23 | + */ |
| 24 | +pub struct Solution {} |
| 25 | +use super::util::tree::{to_tree, TreeNode}; |
| 26 | + |
| 27 | +// submission codes start here |
| 28 | + |
| 29 | +// Definition for a binary tree node. |
| 30 | +// #[derive(Debug, PartialEq, Eq)] |
| 31 | +// pub struct TreeNode { |
| 32 | +// pub val: i32, |
| 33 | +// pub left: Option<Rc<RefCell<TreeNode>>>, |
| 34 | +// pub right: Option<Rc<RefCell<TreeNode>>>, |
| 35 | +// } |
| 36 | +// |
| 37 | +// impl TreeNode { |
| 38 | +// #[inline] |
| 39 | +// pub fn new(val: i32) -> Self { |
| 40 | +// TreeNode { |
| 41 | +// val, |
| 42 | +// left: None, |
| 43 | +// right: None |
| 44 | +// } |
| 45 | +// } |
| 46 | +// } |
| 47 | +use std::cell::RefCell; |
| 48 | +use std::rc::Rc; |
| 49 | +impl Solution { |
| 50 | + pub fn binary_tree_paths(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<String> { |
| 51 | + let mut res = Vec::new(); |
| 52 | + Solution::helper(root, "".to_owned(), &mut res); |
| 53 | + res |
| 54 | + } |
| 55 | + |
| 56 | + fn helper(root: Option<Rc<RefCell<TreeNode>>>, path: String, res: &mut Vec<String>) { |
| 57 | + if let Some(inner) = root { |
| 58 | + if inner.borrow().left.is_none() && inner.borrow().right.is_none() { |
| 59 | + res.push(format!("{}{}", path, inner.borrow().val)); |
| 60 | + } else { |
| 61 | + let path = format!("{}{}->", path, inner.borrow().val); |
| 62 | + Solution::helper(inner.borrow().left.clone(), path.clone(), res); |
| 63 | + Solution::helper(inner.borrow().right.clone(), path, res); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +// submission codes end |
| 70 | + |
| 71 | +#[cfg(test)] |
| 72 | +mod tests { |
| 73 | + use super::*; |
| 74 | + |
| 75 | + #[test] |
| 76 | + fn test_257() { |
| 77 | + assert_eq!(Solution::binary_tree_paths(tree![1,2,3,null,5]), vec_string!["1->2->5", "1->3"]); |
| 78 | + } |
| 79 | +} |
0 commit comments