前序
int preorder_traversal(BTNode * node)
{
if (!node) {
return -1;
}
std::cout << node->elem << " ";
preorder_traversal(node->lchild);
preorder_traversal(node->rchild);
return 0;
}
int preorder_traversalByStack(BTNode * node)
{
if (!node) {
return -1;
}
BSTNode*cur=NULL;
stack<BSTNode*> st;
st.push(node);
while (!st.empty()) {
cur = st.top();
st.pop();
cout << cur->elem << " ";
if (cur->rchild != NULL) {
st.push(cur->rchild);
}
if (cur->lchild != NULL) {
st.push(cur->lchild);
}
}
return 0;
}
中序
void InOrder(TreeNode*root){
if(!root)return ;
InOrder(root->left);
//打印当前结果的值
printf("%d",root->val);
InOrder(root->right);
}
void InOrder(TreeNode*root){
stack<TreeNode*> stk;
while (root != nullptr || !stk.empty()) {
while (root != nullptr) {
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
//打印当前结果的值
printf("%d",root->val);
root = root->right;
}
}
后序
用栈实现简单介绍:
后序是左右根 顺序逆过来就是 根右左
根右左 和前序是不是很相似,仅仅就是把左右调换过来而已
把按照根右左顺序放入到st2中,然后st2一次出栈就得到 左右根的后序遍历了
int postorder_traversal(BSTNode * node)
{
if (!node) {
return -1;
}
postorder_traversal(node->lchild);
postorder_traversal(node->rchild);
std::cout << node->elem << " ";
return 0;
}
int postorder_traversalByStack(BSTNode * node)
{
if (!node) {
return -1;
}
stack<BSTNode*> st1;
stack<BSTNode*> st2;
st1.push(node);
BSTNode* cur=NULL;
while (!st1.empty()) {
cur = st1.top();
st1.pop();
st2.push(cur);
if (cur->lchild) {
st1.push(cur->lchild);
}
if (cur->rchild) {
st1.push(cur->rchild);
}
}
while (!st2.empty()) {
std::cout << st2.top()->elem << " ";
st2.pop();
}
return 0;
}