【问题标题】:Traverse through binary tree遍历二叉树
【发布时间】:2022-11-11 05:22:52
【问题描述】:
use std::cell::RefCell;
use std::rc::Rc;

#[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,
        }
    }

    pub fn invalid_path_error(self) {
        panic!("Invalid path");
    }

    pub fn insert(&mut self, directions: &[&str], val: i32) {
        let mut cur_node = &mut None;

        let l = directions.len();

        if directions[0] == "left" {
            cur_node = &mut self.left;
        }
        if directions[0] == "right" {
            cur_node = &mut self.right;
        }

        for dir in &directions[1..] {
            let mut n;

            if *dir == "left" {
                if let Some(z) = cur_node {
                    n = &mut z.borrow_mut().left;
                } else {
                    panic!("Invalid path");
                }
            }
            if *dir == "right" {
                if let Some(z) = cur_node {
                    n = &mut z.borrow_mut().right;
                } else {
                    panic!("Invalid path");
                }
            }

            cur_node = n;
        }

        //cur_node = Some(Rc::new(RefCell::new(TreeNode::new(2))));
    }
}

我正在尝试通过解决一些 leet 代码问题来学习 rust。我正在尝试为二叉树实现插入功能。这是 leet 代码中给出的结构。我正在尝试通过传递路径的字符串列表来实现插入,例如。向左,向右,向左等。最后遍历后,我将添加新节点。我正在尝试使用 cur 节点作为临时指针,并希望使用每个字符串更改它。但每次我收到此错误时 - “临时值在借用时下降,请考虑使用 let 绑定来创建更长寿命的值”。我该如何解决这个问题并实施 insert ?

货物检查 -

【问题讨论】:

标签: rust binary-tree


【解决方案1】:

这是将Rc&lt;RefCell&lt;_&gt;&gt; 替换为Box&lt;_&gt; 的解决方案。通常,当多人想要拥有基础数据的所有权时,您只需要联系Rc。在这种情况下,每个节点仅由另一个节点拥有,因此Box 更可取。

此解决方案遍历树以找到最后一个节点,然后使用最后一个方向分配给正确的子节点。没有实施检查以确保路径上的节点存在或现有节点没有被覆盖。

#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Box<TreeNode>>,
    pub right: Option<Box<TreeNode>>,
}

impl TreeNode {
    #[inline]
    pub fn new(val: i32) -> Self {
        TreeNode {
            val,
            left: None,
            right: None,
        }
    }

    pub fn insert(&mut self, directions: &[&str], val: i32) {
        let mut cur_node = self;

        let len = directions.len();
        let mut directions = directions.into_iter().copied();
        for direction in directions.by_ref().take(len - 1) {
            let child_node = match direction {
                "left" => &mut cur_node.left,
                "right" => &mut cur_node.right,
                _ => panic!("invalid direction {direction}"),
            };
            cur_node = child_node.as_mut().expect("invalid path").as_mut();
        }

        let new_node = Some(Box::new(TreeNode::new(val)));
        match directions.next().unwrap() {
            "left" => cur_node.left = new_node,
            "right" => cur_node.right = new_node,
            direction @ _ => panic!("invalid direction {direction}"),
        }
    }
}

fn main() {
    let mut tree = TreeNode::new(0);
    tree.insert(&["left"], 1);
    tree.insert(&["right"], 2);
    tree.insert(&["left", "left"], 2);
    tree.insert(&["right", "left"], 3);
    println!("{:#?}", tree);
}

印刷

TreeNode {
    val: 0,
    left: Some(
        TreeNode {
            val: 1,
            left: Some(
                TreeNode {
                    val: 2,
                    left: None,
                    right: None,
                },
            ),
            right: None,
        },
    ),
    right: Some(
        TreeNode {
            val: 2,
            left: Some(
                TreeNode {
                    val: 3,
                    left: None,
                    right: None,
                },
            ),
            right: None,
        },
    ),
}

【讨论】:

  • 尼特:into_iter() 切片 -> iter()。另外,我会在第一个方向而不是最后一个方向上分支:play.rust-lang.org/…
猜你喜欢
  • 2012-01-01
  • 1970-01-01
  • 2021-11-20
  • 2021-03-08
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多