【Leetcode】Populating Next Right Pointers in Each Node II
2015-11-21 15:58
836 查看
题目链接: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:
思路:
1、用"Populating
Next Right Pointers in Each Node".的算法,仍然有效,只是空间复杂度是O(n)
算法1:
题目:
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
思路:
1、用"Populating
Next Right Pointers in Each Node".的算法,仍然有效,只是空间复杂度是O(n)
算法1:
public void connect(TreeLinkNode root) { List<List<TreeLinkNode>> lists = levelOrder(root); for (List<TreeLinkNode> list : lists) { for (int i = 0; i < list.size() - 1; i++) { list.get(i).next = list.get(i + 1); } list.get(list.size() - 1).next = null; } } /** * 统计每层节点 */ public List<List<TreeLinkNode>> levelOrder(TreeLinkNode root) { int height = heightTree(root); List<List<TreeLinkNode>> lists = new ArrayList<List<TreeLinkNode>>(); for (int i = 1; i <= height; i++) { List<TreeLinkNode> list = new ArrayList<TreeLinkNode>(); list = kLevelNumber(root, 1, list, i); lists.add(list); } return lists; } /*** * kk是目标层数,height是当前遍历结点高度 */ public List<TreeLinkNode> kLevelNumber(TreeLinkNode p, int height, List<TreeLinkNode> list, int kk) { if (p != null) { if (height == kk) { list.add(p); } list = kLevelNumber(p.left, height + 1, list, kk); list = kLevelNumber(p.right, height + 1, list, kk); } return list; } public int heightTree(TreeLinkNode p) { if (p == null) return 0; int h1 = heightTree(p.left); int h2 = heightTree(p.right); return h1 > h2 ? h1 + 1 : h2 + 1; }
相关文章推荐
- 2、初识HDFS
- webstorm创建nodejs + express + jade 的web 项目
- 聊天室软件设计-nodejs
- 【Leetcode】Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node II
- node.js的request模块
- Populating Next Right Pointers in Each Node
- node.js 调用天气webservice接口
- node.js 实现一个简单的登录拦截器
- 前端代码发布系统-node开发
- window nodejs 版本切换 nvmw
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node
- Node.js以数据流的方式处理查询数据
- Node.js使用iis管理器中session丢失处理
- 使用node-webkit开发exe窗口程序
- iOS&Node 搭建WebSocketServer实现聊天
- supervisor提高nodejs调试效率
- Node.js 文件系统
- nodejs+express实现文件上传