思考
如何根据递归函数写出相应的迭代函数?
遍历类型
struct node {int value;Node *left;Node *right;};
前序遍历
递归实现
void preorder_rec(BinaryTree *root) {if (!root) {return;}printf("%d\t", root->value);// handler(root->value);preorder_rec(root->left);preorder_rec(root->right);}
非递归
void preorder(BinaryTree *root) {if (!root) {return;}stack<int> st;st.push(root);while(!st.empty()) {Node *temp = st.top();st.pop();printf("%d\t", temp->value);if (temp->right) {st.push(temp->right);}if (temp->left) {st.push(temp->left);}}}
中序遍历
递归实现
void inorder_rec(BinaryTree *root) {if (!root) {return;}printf("%d\t", root->value);// handler(root->value);inorder_rec(root->left);inorder_rec(root->right);}
非递归
后序遍历
递归实现
非递归
层序遍历
递归实现
非递归
总结
递归模板
核心:处理节点函数放在何处
void order_rec(BinaryTree *root) {if (!root) {return;}order_rec(root->left);order_rec(root->right);printf("%d\t", root->value);// handler(root->value);}
非递归模板
合理利用栈或队列实现
