f**********t 发帖数: 1001 | 1 最近在练习用Tree Iterator实现Tree的非递归遍历。想练习一下begin()/end()/++的
版本。code如下:
结果在operator !=那里出了问题:
Line 45: passing ‘const TreeIterator’ as ‘this’ argument of ‘TreeNode*
TreeIterator::getRoot()’ discards qualifiers [-fpermissive]
求教这个怎么fix? 多谢啦 =)
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class TreeIterator {
stack s;
TreeNode *root_;
public:
TreeNode* getRoot() {
return root_;
}
TreeIterator(TreeNode *root) {
if (root) {
s.push(root);
}
}
TreeIterator begin() {
TreeIterator iterator(root_);
return iterator;
}
TreeIterator end() {
TreeIterator iterator(NULL);
return iterator;
}
TreeIterator operator++() {
TreeNode *root = s.top();
s.pop();
if (root->right) {
s.push(root->right);
}
if (root->left) {
s.push(root->left);
}
root_ = s.empty() ? NULL : s.top();
TreeIterator iterator(root_);
return iterator;
}
bool operator!=(const TreeIterator &it) {
return getRoot() != it.getRoot();
}
};
class Solution {
public:
vector preorderTraversal(TreeNode *root) {
vector vec;
TreeIterator iterator(root);
for (TreeIterator it = iterator.begin(); it != iterator.end(); ++it) {
vec.push_back(*it);
}
return vec;
}
}; | z******g 发帖数: 271 | 2 TreeNode* getRoot() const {...} | f**********t 发帖数: 1001 | 3 多谢!现在fixed. :)
inline bool operator!=(const X& lhs, const X& rhs){return !(lhs == rhs);}
看来在!=里面,左右两边的值都得是cost才行。 |
|