Last active
February 12, 2016 01:21
-
-
Save cpjk/ff22a704b3538d74f93b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def connect(self, root): | |
self.do_connect(root, None) | |
def do_connect(self, node, right_sib): | |
if not node: | |
return | |
node.next = right_sib if right_sib else None | |
if node.left: | |
self.do_connect(node.left, right_sib=node.right) | |
if node.right: | |
if right_sib: | |
self.do_connect(node.right, right_sib=right_sib.left) | |
else: | |
self.do_connect(node.right, right_sib=None) | |
def build_tree(self, num_levels, val): | |
root = TreeLinkNode(val) | |
if num_levels > 1: | |
root.left = self.build_tree(num_levels - 1, val*2 + 1) | |
root.right = self.build_tree(num_levels - 1, val*2 + 2) | |
return root | |
class TreeLinkNode(object): | |
def __init__(self, x): | |
self.val = x | |
self.left = None | |
self.right = None | |
self.next = None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment