二叉树和尾递归

二叉树是递归结构,用递归方法来访问是最自然的。下面摘录课本二叉树中序遍历代码,这是最简单大家最熟悉不过的东西了:

#include <stdio.h>
#define visit(tree)   printf("%d ", tree->x)

struct node {
    
    
	int x;
	struct node *left;
	struct node *right;
};

void inorder(struct node *tree) 
{
    
    
	if(tree->left) inorder(tree->left);
	visit(tree);
	if(tree->right) inorder(tree->right);
}

如果把二叉树最右侧的一条链看作链表,而每个元素的左指针看作和自己同构的子结构,则可以得到另一种遍历写法,

void inorder(struct node *tree) 
{
    
    
	while (tree) {
    
    
		if (tree->left) inorder(tree->left);
		visit(tree);
		tree = tree->right;
	}
}

功能相同。但是第二个递归没有了!它变成了一个简单的循环。

同理,汉诺塔的尾递归也可以做这样的优化,要点是,想象尾递归的每一次调用都是二叉树最右侧链表的依次遍历,而在调用过程中,参数向量必有一个分量包含循环结束条件,因而链表是有终点的。

void hanoi(int n,int a,int b, int c)
{
    
    
	if (n==1) printf("move %d -> %d\n", a, c);
	else {
    
    
		hanoi(n-1, a, c, b);
		printf("move %d -> %d\n", a, c);
		hanoi(n-1, b, a, c);
	}
}

void hanoi2(int n,int a,int b, int c)
{
    
    
	int x;
	while (n>1){
    
    
		hanoi2(--n, a, c, b);
		printf("move %d -> %d\n", a, c);
		x=a; a=b; b=x;
	}
	printf("move %d -> %d\n", a, c);
}

最后,是快速排序的一个例子:

void quickSort2(int arr[], int low, int high)
{
    
    
	while (low < high)
	{
    
    
		int pi = partition(arr, low, high);
		quickSort2(arr, low, pi - 1);
		low = pi+1;
	}
}

Guess you like

Origin blog.csdn.net/aaasssdddd96/article/details/121387475