Populating Next Right Pointers in Each Node
2014.1.8 05:59
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 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
Solution:
It looks like this problem is somewhat related to level-order traversal, but the space limit cannot meet the requirement. You can't use constant space to do a level-order traversal. So we'll do it the preorder way.
Left node is next to the right node, while the right node is next to the leftest node you can find on the same level right to this right node.
Well... I guess the code is better explanation for this problem. I wouldn't waste more words than code to show what I'm doing. Please see the codes below.
Time and space complexities are both O(n), where n is the number of nodes in the tree.
Accepted code:
1 // 1AC, nice 2 /** 3 * Definition for binary tree with next pointer. 4 * struct TreeLinkNode { 5 * int val; 6 * TreeLinkNode *left, *right, *next; 7 * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void connect(TreeLinkNode *root) { 13 // IMPORTANT: Please reset any member data you declared, as 14 // the same Solution instance will be reused for each test case. 15 if(root == nullptr){ 16 return; 17 } 18 19 // This algorithm won't work if the tree is not perfect. 20 if(root->left){ 21 TreeLinkNode *ll, *rr; 22 23 ll = root->left; 24 rr = root->right; 25 while(ll != nullptr){ 26 ll->next = rr; 27 ll = ll->right; 28 rr = rr->left; 29 } 30 } 31 connect(root->left); 32 connect(root->right); 33 } 34 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)