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);
}
};
参考代码:
# 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