二叉树及其扩展

二叉树的结构

class Node<V>{
    V value;
    Node left;
    Node right;
}

二叉树的遍历

分别是前序、中序、后续、层序遍历。

//递归实现的前序遍历
    static void preOrderRecur(Node* head){
        if(head == NULL)
            return;
        cout << head->data << " ";
        preOrderRecur(head->left);
        preOrderRecur(head->right);
    }
    //递归实现的中序遍历
    static void inOrderRecur(Node* head){
        if(head == NULL)
            return;
        inOrderRecur(head->left);
        cout << head->data << " ";
        inOrderRecur(head->right);
    }
    //递归实现的后序遍历
    static void posOrderRecur(Node*head){
        if(head == NULL)
            return;
        posOrderRecur(head->left);
        posOrderRecur(head->right);
        cout << head->data << " ";
    }
    //非递归实现的前序遍历
    static void preOrderUnRecur(Node* head){
        if(head == NULL)
            return;
        stack<Node*> s;
        s.push(head);
        while(!s.empty()){
            head = s.top();
            cout << head->data << " ";
            s.pop();
            if(head->right != NULL)
                s.push(head->right);
            if(head->left != NULL)
                s.push(head->left);
        }
    }
    //非递归实现的中序遍历
    static void inOrderUnRecur(Node* head){
        if(head == NULL)
            return;
        stack<Node*> s;
        while(!s.empty()|| head != NULL){
          if(head != NULL){
            s.push(head);
            head = head->left;
          }else{
            head = s.top();
            cout << head->data << " ";
            s.pop();
            head = head->right;
          }
        }
    }
    //非递归实现的后序遍历
    static void posOrderUnRecur_1(Node* head){
    if(head == NULL){
            return;
        }
        stack<Node*> s1;
        stack<Node*> s2;
        s1.push(head);
        while(!s1.empty()){
            head = s1.top();
            s1.pop();
            s2.push(head);
            if(head->left != NULL){
                s1.push(head->left);
            }
            if(head->right != NULL){
                s1.push(head->right);
            }
        }
        while(!s2.empty()){
            cout << s2.top()->data << " ";
            s2.pop();
        }
    }

 

//宽度优先遍历
    static void breadthFirstTravel(Node* head){
        if(head == NULL){
            return;
        }
        queue<Node*> q;
        q.push(head);
        while(!q.empty()){
            head = q.front();
            cout << head->data << " ";
            q.pop();
            if(head->left != NULL){
                q.push(head->
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值