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

[leetcode] Populating Next Right Pointers in Each Node II

2015-06-25 23:48 162 查看
From : https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

You may only use constant extra space.

For example,

Given the following binary tree,

1
/  \
2    3
/ \    \
4   5    7


After calling your function, the tree should look like:

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

Solution 1: 每次从上一层取到下一层的下一个。

/**
* 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) {
bool isLeft=false;
TreeLinkNode *cur=root, *up, *dp, *t=NULL;
while(cur) {
up = cur;
while(up) {
if(!up->left && !up->right) {
up=up->next;
continue;
}
if(up->left) {
isLeft = true;
} else {
isLeft = false;
}
if(!t) {
dp = t = isLeft ? up->left : up->right;
if(isLeft && up->right) {
dp->next = up->right;
dp = dp->next;
}
up=up->next;
continue;
}
dp->next = isLeft ? up->left : up->right;
dp = dp->next;
if(isLeft && up->right) {
dp->next = up->right;
dp = dp->next;
}
up=up->next;
}
cur = t;
t = NULL;
}
}
};


Solution 2:
简化为:

/**
* 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) {
TreeLinkNode* prev = NULL, *nextLevel = NULL;

while(root) {
prev = nextLevel = NULL;
while(root) {
if(nextLevel == NULL) nextLevel = root->left ? root->left : root->right;
if(root->left) {
if(prev) prev->next = root->left;
prev = root->left;
}
if(root->right) {
if(prev) prev->next = root->right;
prev = root->right;
}
root = root->next;
}
root = nextLevel;
}
}
};


/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
*     int val;
*     TreeLinkNode left, right, next;
*     TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode up = root, cur = null, newLevel = null;

while (up != null) {
cur = newLevel = null;
while (up != null) {
if (newLevel == null) {
// 没初始化的时候 想办法初始化
newLevel = up.left != null ? up.left : up.right;
}
if (up.left != null) {
if (cur != null) {
cur.next = up.left;
}
cur = up.left;
}
if (up.right != null) {
if (cur != null) {
cur.next = up.right;
}
cur = up.right;
}
up = up.next;
}
up = newLevel;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: