树的层序遍历
递归
# 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 root is None:return
if root.left: root.left.next=root.right
if root.right:
if root.next:
root.right.next=root.next.left
else:
root.right.next=None
self.connect(root.left)
self.connect(root.right)
非递归
# 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):
head=root
while head:
cur=head
while cur and cur.left:
cur.left.next=cur.right
if cur.next:
cur.right.next=cur.next.left
cur=cur.next
head=head.left
网友评论