美文网首页
116. Populating Next Right Point

116. Populating Next Right Point

作者: 阿团相信梦想都能实现 | 来源:发表于2016-09-20 10:40 被阅读0次
树的层序遍历
递归
# 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
        

相关文章

网友评论

      本文标题:116. Populating Next Right Point

      本文链接:https://www.haomeiwen.com/subject/oitoettx.html