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

LeetCode: Populating Next Right Pointers in Each Node I && II

2015-05-15 11:12 489 查看
Title:

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
思路:使用递归


/**
* 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) {
maker(root,NULL);
}

void maker (TreeLinkNode* first, TreeLinkNode* second){
if (!first)
return ;
first->next = second;
maker(first->left,first->right);
if (second){
maker(first->right,second->left);
maker(second->left,second->right);
}
}
};


非递归就是BFS搜索

/**
* 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)
return ;
queue<TreeLinkNode*> Q;
int pre_count = 1;
int cur_count = 0;
Q.push(root);
while (!Q.empty()){
TreeLinkNode* p = Q.front();//关键
Q.pop();
pre_count--;
if (!Q.empty() && pre_count != 0){
p->next = Q.front();
}

if (p->left){
Q.push(p->left);
cur_count++;
}
if (p->right){
Q.push(p->right);
cur_count++;
}
if (pre_count == 0){
pre_count = cur_count;
cur_count = 0;
}
}
}
};


Title

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

使用上面的非递归
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: