题目描述:给定一个二叉树
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL
。
初始状态下,所有 next 指针都被设置为 NULL
。
说明:
- 你只能使用额外常数空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
示例:
给定二叉树,
1
/ \
2 3
/ \ \
4 5 7
调用你的函数后,该二叉树变为:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
解法1。递归,对每个节点,先找到它的next节点的第一个非空子节点(非左即右),然后安排好自个的右节点指向(如果非空的话)、左节点指向,然后递归遍历右子节点、左子节点,应该是得先把右边处理好了,再找左边吧,这个过程呈现先右后左的趋势。
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if not root:
return
post = root.next
while post:
if post.left:
post = post.left
break
if post.right:
post = post.right
break
post = post.next
if root.right:
root.right.next = post
if root.left:
if root.right:
root.left.next = root.right
else:
root.left.next = post
self.connect(root.right)
self.connect(root.left)
解法2。
# Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if not root:
return
dummy = TreeLinkNode(0)
cur = dummy
while root:
if root.left:
cur.next = root.left
cur = cur.next
if root.right:
cur.next = root.right
cur = cur.next
root = root.next
if not root:
cur = dummy
root = dummy.next
dummy.next = None