每个节点的右向指针
给定一个二叉树
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL
。
初始状态下,所有 next 指针都被设置为 NULL
。
说明:
- 你只能使用额外常数空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
- 你可以假设它是一个完美二叉树(即所有叶子节点都在同一层,每个父节点都有两个子节点)。
示例:
给定完美二叉树,
1
/ \
2 3
/ \ / \
4 5 6 7
调用你的函数后,该完美二叉树变为:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
我的想法是把每一层次存起来, 然后对每一层次修改每个节点的右侧指针
1 # Definition for binary tree with next pointer.
2 # class TreeLinkNode:
3 # def __init__(self, x):
4 # self.val = x
5 # self.left = None
6 # self.right = None
7 # self.next = None
8
9 class Solution:
10 # @param root, a tree link node
11 # @return nothing
12 def connect(self, root):
13 if root is None:
14 return root
15 tree = [[root]]
16 i = 0
17 while i < len(tree):
18 cur = tree[i]
19 layer = []
20 for c in cur:
21 if c.left is not None:
22 layer.append(c.left)
23 if c.right is not None:
24 layer.append(c.right)
25
26 if layer:
27 tree.append(layer)
28
29 i += 1
30 for l in tree:
31 for i in range(len(l)-1):
32 l[i].next = l[i+1]
33