117. Populating Next Pointers in Each Node II
Question
Given a binary tree
1
2
3
4
5
6 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.
Solution
BFS搜索,从右至左将每层节点放入队列。
用一个size记录该层级放入节点的数量,每次循环将size-1,当size归零时放入新一层级的节点。
Code
1 | /* |
117. Populating Next Pointers in Each Node II
https://xuanhe95.github.io/2022/04/21/117-Populating-Next-Pointers-in-Each-Node-II/