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

Populating Next Right Pointers in Each Node II

2014-04-22 12:53 337 查看
/**
* 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* cur = root;
while(cur) {
TreeLinkNode* node = cur;
TreeLinkNode* last = NULL;
cur = NULL;
while(node) {
TreeLinkNode* left = node->left;
TreeLinkNode* right = node->right;
if(left || right) {
if(last) last->next = left ? left : right;
if(left) left->next = right;
if(!cur) cur = left ? left : right;
last = right ? right : left;
}
node = node->next;
}
}
}
};


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. iterative way with CONSTANT extra space.
2. iterative way + queue. Contributed by SUN Mian(孙冕).
3. tail recursive solution.
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: