117 Populating Next Right Pointers in Each Node II
2015-12-17 19:24
721 查看
题目链接:https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
题目:
解题思路:
这题和 116 Populating Next Right Pointers in Each Node 的思路一模一样。实际上,我把 116 的答案直接复制到本题轻松 Accepted 。
具体再说一下思路:
1. 层次遍历二叉树,把层次遍历所需的层队列换成层链表,即每层一个链表
2. 在遍历每一层的过程中,通过一个临时指针 p,将该层的结点链接到一起
3. 每一层遍历完后,返回该层左数第一个结点的引用,也就是该层链表的头结点
4. 在上一层给出的结点链表下,遍历下一层的结点,遍历的过程中重复上述操作
代码实现:
题目:
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
解题思路:
这题和 116 Populating Next Right Pointers in Each Node 的思路一模一样。实际上,我把 116 的答案直接复制到本题轻松 Accepted 。
具体再说一下思路:
1. 层次遍历二叉树,把层次遍历所需的层队列换成层链表,即每层一个链表
2. 在遍历每一层的过程中,通过一个临时指针 p,将该层的结点链接到一起
3. 每一层遍历完后,返回该层左数第一个结点的引用,也就是该层链表的头结点
4. 在上一层给出的结点链表下,遍历下一层的结点,遍历的过程中重复上述操作
代码实现:
/** * Definition for binary tree with next pointer. * public class TreeLinkNode { * int val; * TreeLinkNode left, right, next; * TreeLinkNode(int x) { val = x; } * } */ public class Solution { public void connect(TreeLinkNode root) { if(root == null) return; TreeLinkNode oldHead = root; while(oldHead != null) { TreeLinkNode p = null; TreeLinkNode newHead = p; // 二者并不是指向同一个对象的引用 while(oldHead != null) { if(oldHead.left != null) { if(p == null) { p = oldHead.left; newHead = p; // 二者指向同一个对象的引用 } else { p.next = oldHead.left; p = p.next; } } if(oldHead.right != null) { if(p == null) { p = oldHead.right; newHead = p; // 二者指向同一个对象的引用 } else { p.next = oldHead.right; p = p.next; } } oldHead = oldHead.next; } oldHead = newHead; } } }
61 / 61 test cases passed. Status: Accepted Runtime: 2 ms
相关文章推荐
- Node.js 的Web server--Fenix
- Nodejs源码分析之assert
- Populating Next Right Pointers in Each Node,Populating Next Right Pointers in Each Node II
- NodeManagerMetrics上精确化Container指标监控
- node.js之socket.io模块
- HDFS源码分析(一)-----INode文件节点
- hive日志位置(日志定位报错:Failed with exception Unable to move sourcehdfs://namenode/tmp/hive-pmp_bi/h)
- hive日志位置(日志定位报错:Failed with exception Unable to move sourcehdfs://namenode/tmp/hive-pmp_bi/h)
- nodejs基础 -- 函数
- nodejs基础 -- 模块系统
- Node.js开发框架Express4.x
- Node.js开发框架Express4.x
- 理解node.js
- nodejs基础 -- Stream流
- Undefined symbols for architecture armv7: "std::_List_node_base::hook(std::_List_node_base*)", refer
- nodejs基础 -- EventEmitter
- NODE.JS入门示例
- nodejs开始
- nodeJs中创建服务器
- 从原理上理解NodeJS的适用场景