MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / insert

Method insert

publication/code/chapter08/bst.rs:140–177  ·  view source on GitHub ↗

节点插入

(&mut self, key: T, val: U)

Source from the content-addressed store, hash-verified

138
139 // 节点插入
140 fn insert(&mut self, key: T, val: U) {
141 // 没数据直接插入
142 if self.key.is_none() {
143 self.key = Some(key);
144 self.val = Some(val);
145 } else {
146 match &self.key {
147 Some(k) => {
148 // 存在 key,更新 val
149 if key == *k {
150 self.val = Some(val);
151 return;
152 }
153
154 // 未找到相同 key,需要插入新节点
155 // 先找到需要插入的子树
156 let child = if key < *k {
157 &mut self.left
158 } else {
159 &mut self.right
160 };
161
162 // 根据节点递归下去,直到插入
163 match child {
164 Some(ref mut node) => {
165 node.insert(key, val);
166 },
167 None => {
168 let mut node = BST::new();
169 node.insert(key, val);
170 *child = Some(Box::new(node));
171 },
172 }
173 },
174 None => (),
175 }
176 }
177 }
178
179 // 节点查询
180 fn contains(&self, key: &T) -> bool {

Callers 4

enqueueMethod · 0.45
basicFunction · 0.45
orderFunction · 0.45
enqueueMethod · 0.45

Calls

no outgoing calls

Tested by

no test coverage detected