zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    数值的整数次方
    二进制中1的个数
    SpingBoot 启动自动给MongoDB建库
    Java 依赖冲突的解决办法
    Http协议
    你被限流了吗?
    LeetCode 783. 二叉搜索树节点最小距离
    Leetcode 687. 最长同值路径
    LeetCode 784. 字母大小写全排列
    LeetCode 面试题 08.06. 汉诺塔问题
  • 原文地址:https://www.cnblogs.com/gallien/p/14351852.html
Copyright © 2011-2022 走看看