二叉树的非递归遍历

二叉树递归遍历的时候,将其分为根、左子树、右子树三个部分。

其非递归遍历,也是分为三个部分,通过数据结构“栈”的入栈出栈操作以及其先入后出的特性,实现其遍历。

template<class T>
struct  BinaryTreeNode
{
    T _data;
    BinaryTreeNode<T>* _left;
    BinaryTreeNode<T>* _right;

    BinaryTreeNode(const T& x)
        : _data(x)
        , _left(NULL)
        , _right(NULL)
    {}
};

template<class T>
class BinaryTree
{
    typedef BinaryTreeNode<T> Node;
public:
    BinaryTree()
        :_root(NULL)
    {}

    BinaryTree(T* a, size_t n, const T& invalid)
    {
        size_t index = 0;
        _root = _CreatTree(a, n, invalid, index);
    }

    ~BinaryTree()
    {
        _Destroy(_root);
    }

    void Destroy()//后序遍历释放
    {
        _Destroy(_root);
    }

    //非递归
    //前序
    void PreOrderNonR()
    {
        Node* cur = _root;
        stack<Node*> s;
        while (!s.empty() || cur)
        {
            while (cur)
            {
                s.push(cur);
                cur = cur->_left;
            }

            Node* top = s.top();
            cout << top->_data << " ";
            s.pop;

            cur = top->_right;
        }
        cout << endl;
    }

    //中序
    void InOrderNonR()
    {
        Node* cur = _root;
        stack<Node*> s;
        while (!s.empty() || cur)
        {
            while (cur)
            {
                s.push(cur);
                cur = cur->_left;
            }

            Node* top = s.top();
            cout << top->_data << " ";
            s.pop;

            cur = top->_right;
        }
        cout << endl;
    }
    //后序非递归
    void PostOrderNonR()
    {
        stack<Node*> s;
        Node* prev = NULL;
        Node* cur = _root;
        while (!s.empty() || cur)
        {
            while (cur)
            {
                s.push(cur);
                cur = cur->_left;
            }
            Node* top = s.top();
            if (top->_right = NULL || top->_right == prev)
            {
                cout << top->_data << " ";
                prev = top;
                s.pop();
            }
            else
            {
                cur = top->_right;
            }
        }
        cout << endl;
    }

protected:
    Node* _CreatTree(T* a, size_t n, const T& invalid, size_t& index)
    {
        Node* root = NULL;
        if (index < n&&a[index] != invalid)
        {
            root = new Node(a[index]);
            root->_left = _CreatTree(a, n, invalid, ++index);
            root->_right = _CreatTree(a, n, invalid, ++index);
        }
        return root;
    }

private:
    Node* _root;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值