Last active
August 5, 2017 17:08
-
-
Save cixuuz/9116c671aabd43a479ad47c2e162c74a to your computer and use it in GitHub Desktop.
[116 Populating Next Right Pointers in Each Node] #leetcode
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
# 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 | |
from collections import deque | |
class Solution: | |
# @param root, a tree link node | |
# @return nothing | |
def connect(self, root): | |
if root is None: | |
return | |
queue = deque([root, None]) | |
while not((len(queue) == 1 and queue[0] is None)): | |
node = queue.popleft() | |
if node is None: | |
queue.append(None) | |
else: | |
node.next = queue[0] | |
if node.left is not None: | |
queue.extend([node.left, node.right]) | |
class Solution1: | |
# @param root, a tree link node | |
# @return nothing | |
def connect(self, root): | |
if root is None: | |
return | |
leftmost = root | |
root.next = None | |
while (leftmost and leftmost.left): | |
cur = leftmost | |
while (cur): | |
cur.left.next = cur.right | |
if (cur.next): | |
cur.right.next = cur.next.left | |
else: | |
cur.right.next = None | |
cur = cur.next | |
leftmost = leftmost.left | |
class Solution2: | |
# @param root, a tree link node | |
# @return nothing | |
def connect(self, root): | |
if root is None: | |
return | |
leftmost = root | |
while (leftmost.left): | |
cur = leftmost | |
while (cur): | |
cur.left.next = cur.right | |
if (cur.next): | |
cur.right.next = cur.next.left | |
cur = cur.next | |
leftmost = leftmost.left |
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
public class Solution { | |
public void connect(TreeLinkNode root) { | |
if (root == null) { | |
return; | |
} | |
TreeLinkNode leftmost = root; | |
TreeLinkNode cur = null; | |
while (leftmost.left != null) { | |
cur = leftmost; | |
while (cur != null ) { | |
cur.left.next = cur.right; | |
if (cur.next != null) { | |
cur.right.next = cur.next.left; | |
} | |
cur = cur.next; | |
} | |
leftmost = leftmost.left; | |
} | |
} | |
} | |
public class Solution1 { | |
public void connect(TreeLinkNode root) { | |
if (root == null) { | |
return; | |
} | |
if (root.left != null) { | |
root.left.next = root.right; | |
if (root.next != null) { | |
root.right.next = root.next.left; | |
} | |
} | |
connect(root.left); | |
connect(root.right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment