leetcode@ [116/117] Populating Next Right Pointers in Each Node I & II (Tree, BFS)
2016-03-13 05:11
651 查看
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
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,
After calling your function, the tree should look like:
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
/** * 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 node { public: TreeLinkNode* nd; int lv; node(TreeLinkNode* rhs, int l): nd(rhs), lv(l) {} }; class Solution { public: void connect(TreeLinkNode *root) { if(!root) return; queue<node> q; q.push(node(root, 0)); vector<node> vec; while(!q.empty()) { node top = q.front(); vec.push_back(top); q.pop(); int cur_lv = top.lv; TreeLinkNode* cur_nd = top.nd; if(cur_nd->left) q.push(node(cur_nd->left, cur_lv+1)); if(cur_nd->right) q.push(node(cur_nd->right, cur_lv+1)); } int l = 0, r = 1; while(r < vec.size()) { vec[l].nd->next = NULL; while(r < vec.size() && vec[r].lv == vec[l].lv) { vec[l].nd->next = vec[r].nd; ++l; ++r; } l = r; r = l+1; } vec[vec.size()-1].nd->next = NULL; } };
相关文章推荐
- node模块机制与异步处理详解
- SHUTDOWN_MSG: Shutting down NameNode at java.net.UnknownHostException: datanode:unknown error解决办法
- node建立博客系统遇到的问题,1,乱码。2,multer的使用错误。3使用session问题
- LiveNodeg个数不对/Unauthorized request to start container解决办法
- Swagger UI教程 API 文档神器 搭配Node使用
- Node.js 我为何理解客户端多可见了呢
- mac eclipse nodejs开发
- nodejs--Nodejs单元测试小结
- nodejs--JWT 在前后端分离中的应用与实践
- Remove Nth Node From End of List
- Node.js编写爬虫的基本思路及抓取百度图片的实例分享
- HTML中的Node和Element的区别
- JavaScript中Element与Node的区别,children与childNodes的区别
- Hadoop-异常“could only be replicated to 0 nodes, instead of 1”
- Node.js的Express框架使用上手指南
- leetcode Reverse Nodes in k-Group
- 推荐一个nodejs的promise库
- 利用promise写出更加优美的nodejs程序
- Node.js中Process.nextTick()和setImmediate()的区别
- node浅析-npm自带