コード例 #1
0
ファイル: Bst.cpp プロジェクト: liqiu1987/LeetCode
BSTIterator *bstIteratorCreate(struct TreeNode *root) {
	BSTIterator *pstNode = NULL;
	BSTIterator *pstCurNode = NULL;
	BSTIterator *pstPreNode = NULL;
	BSTIterator *pstPostNode = NULL;
	if (NULL == root){
		return NULL;
	}
	if (NULL != root->left){
		pstPreNode = bstIteratorCreate(root->left);
	}

	pstCurNode = (BSTIterator *)malloc(sizeof(BSTIterator));
	if (NULL == pstCurNode){
		return NULL;
	}
	pstCurNode->next = NULL;
	pstCurNode->val = root->val;

	if (NULL != pstPreNode){
		pstPreNode->next = pstCurNode;
		pstNode = pstPreNode;
	}else {
		pstNode = pstCurNode;
	}

	if (NULL != root->right){
		pstPostNode = bstIteratorCreate(root->right);
		if (NULL != pstPostNode){
			pstCurNode->next = pstPostNode;
		}
	}
	return pstNode;
	  
}
コード例 #2
0
int main(int argc, char const *argv[])
{
	int array[50] = {};
	Tree T;
	int i, Len, balanced;
	Len = 50;

	for (i = 0; i < Len; ++i)
		array[i] = rand() % 100;

	T = NULL;
	for (i = 0; i < Len; ++i)
		T = Insert(array[i], T);

	PreOrderTraverse(T);
	printf("\n");

  struct BSTIterator *iter = bstIteratorCreate(T);
	while (bstIteratorHasNext(iter)) 
		printf("%d\n", bstIteratorNext(iter));
	bstIteratorFree(iter);
	return 0;
}