116. Populating Next Right Point

2016-09-20  本文已影响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
        
上一篇 下一篇

猜你喜欢

热点阅读