由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - Tree Iterator && operator overloading的一个问题
相关主题
一道google面试题新鲜Amazon面经(附参考答案) 顺便求各种大公司refer
GOOG ONSITE 面试Leetcode: Symmetric Tree有没有好的iterative的解法?
写了个symmetric tree的stack based iterative实现,有个bug[leetcode] Maximum Depth of Binary Tree
帮我看一下5行代码大牛帮我看看这哪错了? iterative inorder traversal
请问怎么样才能想到关于tree等比较简洁的答案呢?同时记一下超慢速刷题过半以鼓励自己leetcode上Symmetric Tree这道题怎么用iterative的方法做?
Flatten Binary Tree to Linked List的recursive解法Interview question::
unique binary tree 2 (leetcode)【c++里override输出<<总出错】
树中序遍历,要求左子树用递归,右子树用iteration问一个题目
相关话题的讨论汇总
话题: treenode话题: root话题: iterator话题: tree
进入JobHunting版参与讨论
1 (共1页)
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才行。
1 (共1页)
进入JobHunting版参与讨论
相关主题
问一个题目请问怎么样才能想到关于tree等比较简洁的答案呢?同时记一下超慢速刷题过半以鼓励自己
Time complexityFlatten Binary Tree to Linked List的recursive解法
请教这么一个题:BST maximum sum pathunique binary tree 2 (leetcode)
为啥有两个case不对??Binary Tree Maximum Path Sum树中序遍历,要求左子树用递归,右子树用iteration
一道google面试题新鲜Amazon面经(附参考答案) 顺便求各种大公司refer
GOOG ONSITE 面试Leetcode: Symmetric Tree有没有好的iterative的解法?
写了个symmetric tree的stack based iterative实现,有个bug[leetcode] Maximum Depth of Binary Tree
帮我看一下5行代码大牛帮我看看这哪错了? iterative inorder traversal
相关话题的讨论汇总
话题: treenode话题: root话题: iterator话题: tree