Sunday, September 7, 2014

Leetcode: Populating Next Right Pointers in Each Node @Python

The solution is concise and easy to understand but hard to come up with!
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None

class Solution:
    # @param root, a tree node
    # @return nothing
    def connect(self, root):
        leftwall=root
        while(leftwall):
            across=leftwall
            while across:
                if across.left:
                    across.left.next=across.right
                if across.right and across.next:
                    across.right.next=across.next.left
                across=across.next
            leftwall=leftwall.left

No comments :

Post a Comment