二叉树的序列化和反序列化,二叉树深度、广度优先遍历

二叉树的序列化是将二叉树->字符串等形式

二叉树反序列化是将字符串等形式->二叉树

序列化使用先(中、后)序遍历,反序列化时也使用相应的顺序

通常节点后面跟着一个特殊符号作为节点结束标记如!

空一般用#




深度优先遍历,也就深入的遍历,沿着每一个分支直到走到最后,然后才返回来遍历剩余的节点。二叉树不同于图,图需要标记节点是否已经访问过,因为可能会存在环,而二叉树不会出现环,所以不需要标记。那么,我们只需要一个栈空间,来压栈就好了。因为深度优先遍历,遍历了根节点后,就开始遍历左子树,所以右子树肯定最后遍历。我们利用栈的性质,先将右子树压栈,然后在对左子树压栈。此时,左子树节点是在top上的,所以可以先去遍历左子树。

如下是深度优先遍历的代码:

  1. void DepthFirstTravel(Tree *root)  
  2. {  
  3.     stack<Tree *> s;  
  4.     s.push(root);  
  5.     while(!s.empty())  
  6.     {  
  7.         root = s.top();  
  8.         cout << root->data << " ";  
  9.         s.pop();  
  10.         if(root->rchild != NULL)  
  11.         {  
  12.             s.push(root->rchild);  
  13.         }  
  14.         if(root->lchild != NULL)  
  15.         {  
  16.             s.push(root->lchild);  
  17.         }  
  18.   
  19.     }  
  20. }  



广度优先遍历

  1. void BreadthFirstTravel(Tree *root)  
  2. {  
  3.     queue<Tree *> q;  
  4.     q.push(root);  
  5.     while(!q.empty())  
  6.     {  
  7.         root = q.front();  
  8.         cout << root->data << " ";  
  9.         q.pop();  
  10.         if(root->lchild != NULL)  
  11.         {  
  12.             q.push(root->lchild);  
  13.         }  
  14.         if(root->rchild != NULL)  
  15.         {  
  16.             q.push(root->rchild);  
  17.         }  
  18.     }  
  19. }  

class QuickSort {
public:
    int* quickSort(int* A, int n) {
        // write code here
       Sort(A,0,n-1);
        return A;
    }
    void Sort(int* &A,int start,int end)
        {
        if(start>=end)return;
        
        int i=start;
        int j=end;
        int k=A[i];
        while(i<j)
       {
            while(i<j&&A[j]>k)
            {
                j--;
            }
            if(i<j)
            {
                A[i]=A[j];
                i++;
            }
            while(i<j&&A[i]<k)
            {
                i++;
            }
            if(i<j)
            {
                A[j]=A[i];
                j--;
            }
            A[i]=k;
            Sort(A,start,i-1);
            Sort(A,i+1,end);
       }
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值