[LeetCode] 117. Populating Next Right Pointers in Each Node II
阿新 • • 發佈:2020-07-12
Given a binary tree
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 toNULL
.
Initially, all next pointers are set toNULL
.
Follow up:
- You may only use constant extra space.
- Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
Example 1:
Input: root = [1,2,3,4,5,null,7] Output: [1,#,2,3,#,4,5,7,#] Explanation: Given the above binary tree (Figure A), your function should populate each next
pointer to point to its next right node, just like in Figure B.The serialized output is in level order as connected by the next pointers, with '#'
signifying the end of each level.
Constraints:
- The number of nodes in the given tree is less than
6000
. -100<= node.val <= 100
填充每個節點的下一個右側節點指標 II。題意跟版本一很接近,唯一不同的條件是這次給的樹不一定是完美二叉樹,中間會有一些節點的缺失。要求還是一樣,請不要使用額外空間。
我參考了這個帖子
時間O(n)
空間O(1)
Java實現
1 class Solution { 2 public Node connect(Node root) { 3 // corner case 4 if (root == null) { 5 return root; 6 } 7 8 // normal case 9 Node cur = root; 10 while (cur != null) { 11 Node pre = new Node(); 12 Node temp = pre; 13 while (cur != null) { 14 if (cur.left != null) { 15 temp.next = cur.left; 16 temp = temp.next; 17 } 18 if (cur.right != null) { 19 temp.next = cur.right; 20 temp = temp.next; 21 } 22 cur = cur.next; 23 } 24 // to the next level 25 cur = pre.next; 26 } 27 return root; 28 } 29 }