非递归前序遍历
京东二面笔试题
/* typedef struct { int val; node* left; node* right; } node; 1 2 3 4 5 6 7 */
// 刚开始用的vector前插实现, 面试官说用栈实现一下. void pre_order(node* root) { if (root == NULL) { return; } vector<node*> vec; vec.push_back(root); while (!vec.empty()) { node* cur = vec.begin(); vec.erase(vec.begin()); cout << cur->val << endl; if (cur.right) { vec.push_back(vec.begin(), cur.right); } if (cur.left) { vec.push_back(vec.begin(), cur.left); } } } /* 1 2 3 4 5 6 7 */
// 写着写着发现一样的逻辑 void pre_order(node* root) { if (root == NULL) { return; } stack<node*> stk; stk.push(root); while (!stk.empty()) { node *cur = stk.top(); stk.pop(); cout << cur->val << endl; if (cur->right) { stk.push(cur->right); } if (cur->left) { stk.push(cur->left); } } return; }