Problem
Problem page: https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
Topics: Tree, Depth-first SearchTwo Pointers
Difficulty: Medium
Similar problems: (H) Populating Next Right Pointers in Each II Node, (M) Binary Tree Right Side View
Given a binary tree
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *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.Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,1 / \ 2 3 / \ / \ 4 5 6 7After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
Analysis
The problem guarantees a perfect binary tree (all leaves are on the same level, and every parent has both a left and a right child) and allows only constant extra space. A level-order traversal (see the code for Binary Tree Level Order Traversal) gives the right result if you store the nodes at each level in a list and then link them with next pointers. But the list has to hold a whole level, and the bottom level has about half the nodes, so the extra space is O(n).
When it's time to link the nodes at level k+1, the next pointers at level k are already set from the previous pass. Start at the leftmost node (level_head in the code) and follow next to the right to visit every node at level k.
For each node cur at level k, use cur.left.next = cur.right to link its two children; if cur.next isn't null, cur.right.next = cur.next.left makes the right child point to the next parent's left child.
After each level, move level_head down to level_head.left, the leftmost node at the next level. Stop when level_head has no left child (the leaf level). There's no need to touch the next pointers on the root or the rightmost node at each level. They're already NULL.
The time complexity is O(n), and the only extra space is for the two pointers level_head and cur, which is O(1).
In the follow-up problem Populating Next Right Pointers in Each Node II, the tree can have any shape and nodes can be missing children, so you can't use this code as is. See that post for how to solve it.
Code
1 | # Definition for a binary tree node |
Article link: https://xnerv.wang/en/leetcode-populating-next-right-pointers-in-each-node/
