Populating Next Right Pointers in Each Node II
2014-04-22 12:53
337 查看
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ class Solution { public: void connect(TreeLinkNode *root) { TreeLinkNode* cur = root; while(cur) { TreeLinkNode* node = cur; TreeLinkNode* last = NULL; cur = NULL; while(node) { TreeLinkNode* left = node->left; TreeLinkNode* right = node->right; if(left || right) { if(last) last->next = left ? left : right; if(left) left->next = right; if(!cur) cur = left ? left : right; last = right ? right : left; } node = node->next; } } } };
Follow up for problem "Populating Next Right Pointers in Each Node".
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,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
Solution: 1. iterative way with CONSTANT extra space.
2. iterative way + queue. Contributed by SUN Mian(孙冕).
3. tail recursive solution.
*/
相关文章推荐
- LeetCode: Remove Nth Node From End of List
- window下基于eclipse的Nodejs工程项目配置步骤
- 欲善其功,必先利其器--Nodejs调试技术总结
- Windows环境下的NodeJS+NPM+Bower安装配置步骤
- node.js第十四课(路由控制)
- 【转】Node.js软肋之CPU密集型任务
- 深入浅出NodeJS——数据通信,NET模块运行机制
- window下基于eclipse的Nodejs工程项目配置步骤
- window下基于eclipse的Nodejs工程项目配置步骤
- window下基于eclipse的Nodejs工程项目配置步骤
- window下基于eclipse的Nodejs工程项目配置步骤
- window下基于eclipse的Nodejs工程项目配置步骤
- HDFS: NameNode 和 DataNode
- HDFS学习笔记2 -- 关于Secondary NameNode, Checkpoint Node, Backup Node和High Availability (HA)
- nodejs express 配置不成功
- node-webkit教程(9)native api 之Tray(托盘)
- nodejs简介
- (C#) Parse xml 时, 返回的node值总是null。
- [LeetCode] Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node