您的位置:首页 > Web前端 > Node.js

LeetCode(Oct28'12):Populating Next Right Pointers in Each Node

2013-05-16 17:26 399 查看
第一次做LeetCode,选了一道简单一点的题目,先熟悉一下环境。

题目如下:

Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}


Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to
NULL
.

Initially, all next pointers are set to
NULL
.

Note:

You may only use constant extra space.

You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,

Given the following perfect binary tree,

1
/  \
2    3
/ \  / \
4  5  6  7


After calling your function, the tree should look like:

1 -> NULL
/  \
2 -> 3 -> NULL
/ \  / \
4->5->6->7 -> NULL

其实就是给一棵完全二叉树,把同一层的节点用链表穿起来,链表的结构在树节点里也已经给出。下面是实现:

class Solution {
public:
void connect(TreeLinkNode *root) {
for(;root!=NULL;root=root->left)
{
createConnect(root->left,root);
}
}

void createConnect(TreeLinkNode *dest,TreeLinkNode *parent)
{
if(dest==NULL) return;
TreeLinkNode *tmpP,*tmpD;
dest->next=parent->right;
for(tmpP=parent->next,tmpD=dest->next;tmpP!=NULL;tmpP=tmpP->next,tmpD=tmpD->next->next)
{
tmpD->next=tmpP->left;
tmpD->next->next=tmpP->right;
}
}
};


程序很简单,没啥算法可言。由上到下,循环遍历每个层,遍历的时候带着父辈的节点,因为父辈节点已经形成了链式结构,所以挨个给该层节点的next赋值就行了。

说说碰到的问题:

1、当然是输入NULL节点,不考虑的话,会报Runtime Error。

2、只有一个节点,一样,考虑好节点各个指针的NULL情况。

3、在连接完第一个父节点的两个孩子后,没有把当前处理的节点后移,导致在层数 >=4的情况下,中间的节点只会内部连接起来,而不会连接到整个链上(因为被跳过了)。最后只有父节点为上一层第一个和最后一个的孩子节点被连接起来。

PS. csdn的编辑器,也太难用了吧。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: