[LeetCode] Populating Next Right Pointers in Each Node II
The problem becomes more difficult once the binary tree is not perfect. The idea is still similar to use a level-order traversal. Note that we do not need to maintain a queue for the traversal becase the next pointer has provided us with the required information.
The following code is taken from the last answer of this link, which is concise and clean. The use of a dummy node simplifies the code. You may play with the code on some examples to see how it works.
1 class Solution { 2 public: 3 void connect(TreeLinkNode *root) { 4 TreeLinkNode* dummy = new TreeLinkNode(0); 5 dummy -> next = root; 6 while (dummy -> next) { 7 TreeLinkNode* pre = dummy; 8 TreeLinkNode* cur = dummy -> next; 9 pre -> next = NULL; 10 while (cur) { 11 if (cur -> left) { 12 pre -> next = cur -> left; 13 pre = pre -> next; 14 } 15 if (cur -> right) { 16 pre -> next = cur -> right; 17 pre = pre -> next; 18 } 19 cur = cur -> next; 20 } 21 } 22 } 23 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步