use std::rc::Rc; use std::cell::RefCell; use std::borrow::Borrow;
impl Solution { fn dfs(root: Option<Rc<RefCell<TreeNode>>>, parent: Option<Rc<RefCell<TreeNode>>>, l: usize) -> usize { if let Some(node) = root { let mut length = l; if let Some(p) = parent { if RefCell::borrow(&p).val + 1 == RefCell::borrow(&node).val { length += 1; } else { length = 1; } } else { length = 1; } return std::cmp::max(length, std::cmp::max(Self::dfs(RefCell::borrow(&node).left.clone(), Some(node.clone()), length), Self::dfs(RefCell::borrow(&node).right.clone(), Some(node.clone()), length))); } else { return l; }
return 0; } pub fn longest_consecutive(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { return Self::dfs(root, None, 0) as i32; } }
|