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

[leetcode] 116.Populating Next Right Pointers in Each Node

2015-08-25 22:04 573 查看
题目:

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

/ \ / \

题意:

给定一棵二叉树,现在加入了一个next指针,现在需要将next指向该节点同一层的右边的那个节点。要求使用常量额外空间。

思路:

由题目可以看出来这道题需要层次遍历,之前层次遍历的方法是使用队列,每一层逐渐访问,在这道题目里,我们依旧使用层次遍历的方法,只不过这里由于每一层已经使用next连接起来了,所以在遍历下一层的时候,由于上一层已经可以通过一直访问节点的next指针进行层次遍历。对于上一层的节点levelNode,如果存在孩子,那么首先将其左孩子的next指向其右孩子。并且右孩子的next指向levelNode->next->left。即上一层层次遍历的下一个元素的左节点。

以上。

代码如下:

/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
*  int val;
*  TreeLinkNode *left, *right, *next;
*  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if(root == NULL)return;
TreeLinkNode* levelNode = root;
while(levelNode->left != NULL) {
TreeLinkNode* temp = levelNode->left;
while(levelNode->next != NULL) {
levelNode->left->next = levelNode->right;
levelNode->right->next = levelNode->next->left;
levelNode = levelNode->next;
}
levelNode->left->next = levelNode->right;
levelNode = temp;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: