首页 > 代码库 > LeetCode "Populating Next Right Pointers in Each Node"
LeetCode "Populating Next Right Pointers in Each Node"
Apparently BFS is the most obvious one.. but it is not that simple - only constant extra space is provided.
Then the only strategy to take is recursion. I bogged down for quite while.. only after checked http://leetcode.com/2010/03/first-on-site-technical-interview.html, I got enlightment: pick a pen and a piece of paper, and simulate the procedure by drawing - this strategy is working so well on diagram-like problems! Just like "starting from enumeration and check pattern" strategy, a good solution starts from basics.
class Solution {public: void connect(TreeLinkNode *p) { if (!p) return; if (p->left) p->left->next = p->right; // with the same parent if (p->right) p->right->next = (p->next) ? p->next->left : NULL; connect(p->left); connect(p->right); }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。