leetcode-剑指32-I-OK

// language c
// 剑指32-I
// https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* levelOrder(struct TreeNode* root, int* returnSize){
	if(root==NULL){
		returnSize[0]=0;
		return NULL;
	}
	struct TreeNode* Queue[1000];
	int tail = 1;	// 指向下一个入队的元素要待的位置
	int head = 0;	// 指向下一个要出来的元素
	Queue[0] = root;
	void Enqueue(struct TreeNode* in){
		Queue[tail] = in;
        tail = (tail+1)%1000;
	}

	struct TreeNode* Dequeue(){
        head = (head+1)%1000;
        if(head ==0)
            return Queue[999];
		return Queue[head-1];
	}

	bool empty(){
		if(head==tail)
			return true;
		return false;
	}

	// 先数个数
	int count =0;
	void GetNodeNum(struct TreeNode* root){
		if(root!=NULL)
			count++;
        else
            return;
		GetNodeNum(root->left);
		GetNodeNum(root->right);
	}
	GetNodeNum(root);
	// 至此count已经是总个数了,接下来分配空间
	returnSize[0] = count;
	int * ans = (int*)malloc(sizeof(int)*count);
	int fillnext=0;
	void FillAnswer(int n){
		ans[fillnext++]=n;
	}

	struct TreeNode* p;
	while(!empty()){
		p = Dequeue();
		FillAnswer(p->val);
		if(p->left!=NULL)
			Enqueue(p->left);
		if(p->right!=NULL)
			Enqueue(p->right);
	}

	return ans;
}
posted @ 2021-01-31 11:21  RougeBW  阅读(41)  评论(0编辑  收藏  举报