``` #include <bits/stdc++.h> using namespace std; struct node { int val; node* left; node* right; node() : val(-1),left(nullptr),right(nullptr) {} node(int v) : val(v),left(nullptr),right(nullptr) {} }; class tree { stack<node*> s; node* root; public: tree(node* root) { root->val = 5; node* l = new node(4); node* r = new node(6); node* ll = new node(1); node* rr = new node(2); root->left = l,root->right = r,l->left = ll,l->right = rr; this->root = root; } node* nxt() { while(root) { s.push(root); root = root->left; } if(s.empty()) return nullptr; node* tp = s.top(); s.pop(); if(tp->right) s.push(tp->right); return tp; } }; int main() { node* t = new node(); tree* test = new tree(t); cout << test->nxt()->val << '\n'; // 1 cout << test->nxt()->val << '\n'; // 4 cout << test->nxt()->val << '\n'; // 2 cout << test->nxt()->val << '\n'; // 5 cout << test->nxt()->val << '\n'; // 6 return 0; } ``` 代码复盘
点赞 评论

相关推荐

牛客网
牛客企业服务