1. 程式人生 > >編寫演算法交換二叉樹中所有節點的左右子樹

編寫演算法交換二叉樹中所有節點的左右子樹

實現程式碼如下:

非遞迴演算法:

//root是根節點
void swap(){
	BiNode * queue[100], * temp, * root1;
	int first = 0, last = 0;
	queue[first++] = root;
	while(first != last){
		root1 = queue[++last];
		temp = root1->lchild;
		root1->lchild = root1->rchild;
		root1->rchild = temp;
		if(root1->lchild != NULL)
			queue[first++] = root1->lchild;
		if(root1->rchild != NULL)
			queue[first++] = root1->rchild;
	}
}


遞迴演算法:

root是根節點
BiNode * temp, * root1;
void swap(BiNode root1){
	if(root1 == NULL) return;
        else{
		temp = root1->lchild;
		root1->lchild = root1->rchild;
		root1->rchild = temp;
		swap(root1->lchild);
		swap(root1->rchild);
	}
}