use std::rc::Rc; use std::cell::RefCell; impl Solution { fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, path: String, ans: &mut Vec<String>) { let map = vec!['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; if let Some(n) = root { let mut val = map[RefCell::borrow(n).val as usize].to_string(); val.push_str(&path);
if RefCell::borrow(&n).left.is_none() && RefCell::borrow(&n).right.is_none() { ans.push(val.clone()); return; } if !RefCell::borrow(&n).left.is_none() { Self::dfs(RefCell::borrow(&n).left.as_ref(), val.clone(), ans); } if !RefCell::borrow(&n).right.is_none() { Self::dfs(RefCell::borrow(&n).right.as_ref(), val.clone(), ans); } } }
pub fn smallest_from_leaf(root: Option<Rc<RefCell<TreeNode>>>) -> String { let mut ans = vec![]; Self::dfs(Some(&root.unwrap()), "".to_string(), &mut ans); ans.sort(); return ans[0].clone(); } }
|