【慢速学数据结构】树的遍历

来源:互联网 发布:直播软件收入排行榜 编辑:程序博客网 时间:2024/06/16 06:13

这虽然是个easy的话题,但我们还是要争取写出简洁和优雅的代码。

递归形式:前中后序对应的是print的位置,这里只写前序遍历。

void traverse(TreeNode *t){    if(!t) return;    print(t->val);    traverse(t->left);    traverse(t->right);}

非递归形式:

// 前序遍历void iterativePreorder(TreeNode *t){    if(!t) return;    std::stack<TreeNode*> st;    st.push(t);    while(!st.empty())    {        TreeNode *n = st.top();        st.pop();        print(n->val);        if(n->right)            st.push(n->right);        if(n->left)            st.push(n->left);    }}// 中序遍历void iterativeInorder(TreeNode *t){    if(!t) return;    std::stack<TreeNode*> st;    TreeNode *current = t;    bool done = 0;    while(!done)    {        // 一直往左,直到没有左儿子        if(current != nullptr)        {            st.push(current);            current = current->left;        }        else        {            if(!st.empty())             {                           TreeNode *n = st.top();                st.pop();                print(n->val);                current = n->right;            }            else                done = 0;        }    }}// 后序遍历void iterativePostorder(TreeNode *t){    if(!t) return;    std::stack<TreeNode*> s1;    std::stack<TreeNode*> s2;    s1.push(t);    TreeNode *n;    while (!s1.empty())    {        n = s1.top();        s1.pop();        s2.push(n);        if (n->left)            s1.push(n->left);        if (n->right)            s1.push(n->right);    }    while (!s2.empty()    {        n = s2.top();        s2.pop();        printf(n->val);    }}
0 0