I am trying to solve some Leetcode problems with Rust. However, I ran into some difficulties with LeetCode\'s TreeNode
implementation.
use std:
Unwrap and access
T
from anOption<Rc<RefCell<T>>>
You really don't want to try to remove the value from the Option
, the Rc
or the RefCell
via unwrap
/ try_unwrap
/ into_inner
. Instead, pattern match on the Option
and then call borrow
on the RefCell
to get a reference to the T
.
Additionally:
if let
instead of a match
statement when you only care about one arm.snake_case
. V
is not an appropriate name.ret
.pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
fn helper(node: &Option<Rc<RefCell<TreeNode>>>, ret: &mut Vec<i32>) {
if let Some(v) = node {
let v = v.borrow();
helper(&v.left, ret);
ret.push(v.val);
helper(&v.right, ret);
}
}
let mut ret = vec![];
if let Some(v) = root {
helper(&Some(v), &mut ret);
}
ret
}
Personally, I'm not a fan of being forced to construct the Some
, so I'd probably reorganize the code, which also allows me to stick it as a method on TreeNode
:
impl TreeNode {
pub fn inorder_traversal(&self) -> Vec<i32> {
fn helper(node: &TreeNode, ret: &mut Vec<i32>) {
if let Some(ref left) = node.left {
helper(&left.borrow(), ret);
}
ret.push(node.val);
if let Some(ref right) = node.right {
helper(&right.borrow(), ret);
}
}
let mut ret = vec![];
helper(self, &mut ret);
ret
}
}
See also: