117. Populating Next Right Pointers in Each Node II - Medium
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.
- Recursive approach is fine, implicit stack space does not count as extra space for this problem.
Example:
Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
这题和 116. Populating Next Right Pointers in Each Node - Medium 不同的是本题的树不是perfect tree,每个节点并不是都有左右子节点
用dummy指向每层的首节点的前一个节点,用cur遍历这一层,然后连下一层的next。从root开始,如果左子节点存在,cur的next连上左子节点,然后cur指向其next指针;如果右子节点存在,cur的next连右子节点,然后cur指向其next指针。此时移动root,指向其next指针,如果此时root为null,说明当前层已经遍历完,重置cur为dummy结点,root此时为dummy.next,即下一层的首节点,然后dummy的next指针清空
time: O(n), space: O(1)
/** * Definition for binary tree with next pointer. * public class TreeLinkNode { * int val; * TreeLinkNode left, right, next; * TreeLinkNode(int x) { val = x; } * } */ public class Solution { public void connect(TreeLinkNode root) { if(root == null) { return; } TreeLinkNode dummy = new TreeLinkNode(0); TreeLinkNode cur = dummy; while(root != null) { if(root.left != null) { cur.next = root.left; cur = cur.next; } if(root.right != null) { cur.next = root.right; cur = cur.next; } root = root.next; if(root == null) { cur = dummy; root = dummy.next; dummy.next = null; } } } }