GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coding-problems/Trees/populating_next_pointers_tree.py at master · prwitt/coding-problems Expand file tree/ Copy pathpopulating_next_pointers_tree.pyMore file actions 61 lines (48 loc) · 1.45 KB / Copy pathpopulating_next_pointers_tree.pyFile metadata and controls61 lines (48 loc) · 1.45 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 ''' Populating Next Right Pointers in Each Node You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. ========================================= Breadth first (level order) traversal, using queue. Save the previous node and level and if the current level is same then make the previous node to point to the current node. Time Complexity: O(N) Space Complexity: O(N) ''' ############ # Solution # ############ from collections import deque # Definition for a Node. class Node: def __init__(self, val, left, right, next): self.val = val self.left = left self.right = right self.next = next def populating_next_pointers_tree(root): previous = None queue = deque() queue.append((root, 0)) while queue: el = queue.popleft() node = el[0] lvl = el[1] if node is None: continue if (previous is not None) and (lvl == previous[1]): previous[0].next = node previous = (node, lvl) lvl += 1 queue.append((node.left, lvl)) queue.append((node.right, lvl)) return root |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |