# Safety This is highly unsafe, due to pointer 时间复杂度 O(n), 空间复杂度 O(1) 大概思路:当一个node有left subtree时,需要遍历left subtree 的各节点,完成left subtree的遍历,需要回溯到node,这个回 溯指针记录在left_child.right中 点评:利用tree本身的node记录回溯指针(避免用栈记录回溯), 使得空间复杂度由 O(n) => O(1)
(tree: &mut Tree<K, V>)
| 149 | /// 点评:利用tree本身的node记录回溯指针(避免用栈记录回溯), |
| 150 | /// 使得空间复杂度由 O(n) => O(1) |
| 151 | pub unsafe fn morris<K, V>(tree: &mut Tree<K, V>) -> Vec<K> |
| 152 | where |
| 153 | K: Copy, |
| 154 | { |
| 155 | let mut results = vec![]; |
| 156 | let mut cur = tree.root; |
| 157 | |
| 158 | while let Some(node) = cur { |
| 159 | match node.as_ref().left { |
| 160 | Some(left) => { |
| 161 | let mut record = left; |
| 162 | |
| 163 | //traverse right subtree, find前驱node |
| 164 | loop { |
| 165 | match record.as_ref().right { |
| 166 | Some(r) if r != node => record = r, |
| 167 | _ => break, |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | match record.as_ref().right { |
| 172 | Some(_r) => { |
| 173 | //已线索化 |
| 174 | cur = node.as_ref().right; |
| 175 | record.as_mut().right = None; |
| 176 | } |
| 177 | None => { |
| 178 | results.push(node.as_ref().key); |
| 179 | |
| 180 | //未线索化 |
| 181 | record.as_mut().right = cur; |
| 182 | cur = Some(left); |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | None => { |
| 187 | results.push(node.as_ref().key); |
| 188 | //无left subtree, 直接跨到right subtree |
| 189 | cur = node.as_ref().right; |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | results |
| 195 | } |
| 196 | |
| 197 | /// # Safety |
| 198 | /// |