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

Leetcode_populating-next-right-pointers-in-each-node-ii(updated c++ version)

2014-05-05 10:05 330 查看
地址:http://oj.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


思路:
在遍历第 x 层节点时,确定 x+1层节点的 next 关系
用指针last记录上一个节点,并通过更新last来形成节点的next关系
nxt记录下一层的第一个节点
参考代码:
class Solution {
public:
void connect(TreeLinkNode *root) {
if(!root)
return;
TreeLinkNode *p = root, *last = NULL, *nxt = NULL;
while(p)
{
if(p->left)
{
if(!last)
last = p->left;
else
last = last->next = p->left;
if(!nxt)
nxt = p->left;
}
if(p->right)
{
if(!last)
last = p->right;
else
last = last->next = p->right;
if(!nxt)
nxt = p->right;
}
p = p->next;
}
connect(nxt);
}
};


思路:用python里的dictionary,类似c++的map,代码实现需要一点trick,有额外空间
参考代码:
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None

class Solution:
# @param root, a tree node
# @return nothing
def connect(self, root):
if not root: return
s={0: [root]}
cur = 0
while 1:
if not s.has_key(cur):
break
li = s[cur]
for i in li:
if i.left:
if s.has_key(cur+1):
s[cur+1][-1].next = i.left
s[cur+1].append(i.left)
else:
s[cur+1] = [i.left]
if i.right:
if s.has_key(cur+1):
s[cur+1][-1].next = i.right
s[cur+1].append(i.right)
else:
s[cur+1] = [i.right]
cur += 1
return
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: