Say I have a complete binary tree, and I want to get its height or depth. Here's my code:
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None
}
}
}
use std::rc::Rc;
use std::cell::RefCell;
fn get_depth(r: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
if r.is_none() {
return 0;
}
1 + Self::get_depth(&r.as_ref().unwrap().borrow().left)
}
And then I want to use non-recursive code to solve this problem, but it cannot compile. How should I fix it:
fn get_depth(r: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut cur = r;
let mut count = 0;
while cur.is_some() {
count+=1;
cur = &cur.as_ref().unwrap().borrow().left; // err: borrow creates a temporary var...
}
count
}