二叉树的序列化是将二叉树->字符串等形式
二叉树反序列化是将字符串等形式->二叉树
序列化使用先(中、后)序遍历,反序列化时也使用相应的顺序
通常节点后面跟着一个特殊符号作为节点结束标记如!
空一般用#
深度优先遍历,也就深入的遍历,沿着每一个分支直到走到最后,然后才返回来遍历剩余的节点。二叉树不同于图,图需要标记节点是否已经访问过,因为可能会存在环,而二叉树不会出现环,所以不需要标记。那么,我们只需要一个栈空间,来压栈就好了。因为深度优先遍历,遍历了根节点后,就开始遍历左子树,所以右子树肯定最后遍历。我们利用栈的性质,先将右子树压栈,然后在对左子树压栈。此时,左子树节点是在top上的,所以可以先去遍历左子树。
如下是深度优先遍历的代码:
- void DepthFirstTravel(Tree *root)
- {
- stack<Tree *> s;
- s.push(root);
- while(!s.empty())
- {
- root = s.top();
- cout << root->data << " ";
- s.pop();
- if(root->rchild != NULL)
- {
- s.push(root->rchild);
- }
- if(root->lchild != NULL)
- {
- s.push(root->lchild);
- }
- }
- }
广度优先遍历
- void BreadthFirstTravel(Tree *root)
- {
- queue<Tree *> q;
- q.push(root);
- while(!q.empty())
- {
- root = q.front();
- cout << root->data << " ";
- q.pop();
- if(root->lchild != NULL)
- {
- q.push(root->lchild);
- }
- if(root->rchild != NULL)
- {
- q.push(root->rchild);
- }
- }
- }
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);
}
}
};