【发布时间】:2016-01-13 05:59:13
【问题描述】:
我正在尝试在 C 中做 this problem on Leetcode。
给定以下二叉树,
1
/ \
2 3
/ \ \
4 5 7
调用你的函数后,树应该是这样的:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
我正在做的是为树的级别顺序遍历创建一个队列 并将每个节点的下一个指针连接到每个节点的下一个队列节点 等级。为了分隔级别,我将 NULL 指针加入队列。
所以对于上面的例子:: 队列是 -> [1,#, 2,3,#,4,5,7,#] 其中 # 为 NULL ptr。
这是我的问题代码::
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* struct TreeLinkNode *left, *right, *next;
* };
*
*/
bool isEmpty(int start,int end){
if(start > end)
return true;
return false;
}
void connect(struct TreeLinkNode *root) {
if(!root || (!root->left && !root->right))
return;
int cap = 1000;
struct TreeLinkNode** q = malloc(cap* sizeof(struct TreeLinkNode*));
int start=0, end=-1, curLevel=1, nextLevel=0;
// enqueue
q[++end] = root;
while(isEmpty(start, end) == false){
//dequeue
struct TreeLinkNode* temp = q[start++];
curLevel--;
if(isEmpty(start, end) == false && curLevel !=0)
temp->next = q[start];
if(temp->left){
q[++end] = temp->left;
nextLevel++;
}
if(temp->right){
q[++end] = temp->right;
nextLevel++;
}
if(curLevel ==0){
curLevel = nextLevel;
nextLevel =0;
}
if(start> cap-50 || end> cap-50)
q = realloc(q, 2*cap*sizeof(struct TreeLinkNode *));
}
free(q);
}
代码显然适用于小型测试用例,但对于 Leetcode 上的大型测试用例,代码会产生运行时错误。 我不知道我做错了什么。 请帮忙。如果有人可以在 Leetcode 上运行此代码,我将不胜感激
【问题讨论】:
-
根据您写的内容,您似乎过于频繁地将 NULL 指针排队:它应该在每个级别之后,但在您的代码中,它在每个分析的节点之后。
-
你是对的。为了解决这个问题,我做了一些改动。但是代码仍然无法正常工作。
-
是的,感谢您指出错误
标签: c tree queue tree-traversal