// Preorder traversal whileletSome(node) = p { vec.push(node.clone()); // Push the right child node onto the stack ifletSome(right) = node.borrow().right.clone() { stack.push(right); } // Push the left child node onto the stack; if the left child is empty, pop the stack; otherwise p = Some(left) ifletSome(left) = node.borrow().left.clone() { p = Some(left); } else { p = stack.pop(); } } foriin0..vec.len() { letnode = vec[i].clone(); node.borrow_mut().left = None; if i + 1 < vec.len() { node.borrow_mut().right = Some(vec[i + 1].clone()); } else { node.borrow_mut().right = None; } } } }
#include<vector> #include<stack> using std::stack; using std::vector;
classSolution { public: voidflatten(TreeNode *root) { if (root == nullptr) return; int i, n; vector<TreeNode *> link;
stack<TreeNode *> stk; TreeNode *p = root;
while (p || !stk.empty()) { if (p) { link.push_back(p); stk.push(p); p = p->left; } else { p = stk.top(); stk.pop(); p = p->right; } } n = link.size(); for (i = 0; i < n - 1; i++) { link[i]->right = link[i + 1]; link[i]->left = nullptr; } link[n - 1]->right = nullptr; link[n - 1]->left = nullptr; } };
The in-place solution is a variant of Morris traversal. Morris traversal points the predecessor node’s right child to the current node; here, the predecessor node’s right child points to the current node’s right child. This animation in the LeetCode solution is particularly helpful for understanding.