117. Populating Next Right Pointers in Each Node II
2015-08-12 14:19
651 查看
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space. For example, Given the following binary tree,
After calling your function, the tree should look like:
不同于上一题,这题的二叉树并不是完全二叉树,我们不光需要提供first指针用来表示一层的第一个元素,同时也需要使用另一个lst指针表示该层上一次遍历的元素。那么我们只需要处理好如何设置last的next指针就可以了。
代码如下:
9.14
------------
这道题的关键之处就在于想清楚最后两层。!!!!!!
Note:
You may only use constant extra space. For example, Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
不同于上一题,这题的二叉树并不是完全二叉树,我们不光需要提供first指针用来表示一层的第一个元素,同时也需要使用另一个lst指针表示该层上一次遍历的元素。那么我们只需要处理好如何设置last的next指针就可以了。
代码如下:
class Solution { public: void connect(TreeLinkNode *root) { if(!root) { return; } TreeLinkNode* p = root; TreeLinkNode* first = NULL; TreeLinkNode* last = NULL; while(p) { //设置下层第一个元素 if(!first) { if(p->left) { first = p->left; } else if(p->right) { first = p->right; } } if(p->left) { //如果有last,则设置last的next if(last) { last->next = p->left; } //last为left last = p->left; } if(p->right) { //如果有last,则设置last的next if(last) { last->next = p->right; } //last为right last = p->right; } //如果有next,则转到next if(p->next) { p = p->next; } else { //转到下一层 p = first; last = NULL; first = NULL; } } } };
9.14
------------
这道题的关键之处就在于想清楚最后两层。!!!!!!
相关文章推荐
- 116. Populating Next Right Pointers in Each Node
- 利用promise写出更加优美的nodejs程序
- 在 Node.js 中用 Q 实现 Promise – Callback 之外的另一种选择
- NodeJs教程
- Node.js async in practice: When to use what?
- 在Node.js中使用promise摆脱回调金字塔
- Node.js 常见面试题
- Leetcode#19||Remove Nth Node From End of List
- node.js--Less
- [转]Nodejs开发框架Express4.x开发手记
- LeetCode题解:Delete Node in a Linked List
- Remove Nth Node From End of List
- HtmlParser初探--使用Nodefilter和Visitor进行网页分析
- [LeetCode] Count Complete Tree Nodes
- [leetcode-116]Populating Next Right Pointers in Each Node(c++)
- cassandra nodejs driver maillist link
- Node.js详细解析
- 【LeetCode-面试算法经典-Java实现】【116-Populating Next Right Pointers in Each Node(二叉树链接右指针)】
- 我用的一些Node.js开发工具、开发包、框架等总结
- HDU 4587 TWO NODES 枚举+割点