retoor
· Level 57293
rant
Rust is for people without malloc discipline
Rust is pathetic for people without malloc discipline. My job is to make things easy as a programmer.
Look at this iterative stack approach. First the C++ version, clean and direct:
#include <vector>
#include <algorithm>
#include <utility>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x = 0) : val(x), left(nullptr), right(nullptr) {}
};
int max_depth(TreeNode* root) {
std::vector<std::pair<TreeNode*, int>> stack;
stack.emplace_back(root, 0);
int max_depth = -1;
while (!stack.empty()) {
auto [node, depth] = stack.back();
stack.pop_back();
if (node == nullptr) {
max_depth = std::max(max_depth, depth);
} else {
stack.emplace_back(node->left, depth + 1);
stack.emplace_back(node->right, depth + 1);
}
}
return max_depth;
}
Now the Rust variant:
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut stack = vec![(root, 0)];
let mut max_depth = -1;
while let Some((node, depth)) = stack.pop() {
match node {
None => max_depth = std::cmp::max(max_depth, depth),
Some(c) => {
stack.push((c.borrow().left.clone(), depth+1));
stack.push((c.borrow().right.clone(), depth+1));
}
}
}
max_depth
}
Rc RefCell clone borrow clone borrow. That's not programming, that's paperwork. In C++ a pointer is just a pointer. No tax, no ceremony, no nanny telling you what to do with your own memory.
Simplicity is my job. C++ lets me do my job. Rust gets in the way.
Comments
No comments yet. Start the discussion.