LeetCode 117 Populating Next Right Pointers in Each Node II (链表 层次遍历 推荐)
来源:互联网 发布:淘宝客app制作 编辑:程序博客网 时间:2024/06/16 07:35
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
题目分析:和Populating Next Right Pointers in Each Node那题比本题不保证是满二叉树,因此如果用那题的做法将会非常麻烦,需要判断很多null的情况,换个角度思考,模拟一下树层次遍历的过程,给每一层加一个头结点,就可以解决这个问题。1ms
/** * 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) { TreeLinkNode lastNode = root; while (lastNode != null) { TreeLinkNode cur = new TreeLinkNode(0); TreeLinkNode curHead = cur; while (lastNode != null) { if (lastNode.left != null) { cur.next = lastNode.left; cur = cur.next; } if (lastNode.right != null) { cur.next = lastNode.right; cur = cur.next; } lastNode = lastNode.next; } lastNode = curHead.next; } }}
0 0
- LeetCode 117 Populating Next Right Pointers in Each Node II (链表 层次遍历 推荐)
- LeetCode 117 Populating Next Right Pointers in Each Node II
- LeetCode: Populating Next Right Pointers in Each Node II [117]
- LeetCode 117 Populating Next Right Pointers in Each Node II
- [leetcode 117] Populating Next Right Pointers in Each Node II
- [LeetCode 117]Populating Next Right Pointers in Each Node II
- leetcode || 117、Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II - LeetCode 117
- leetcode[117]:Populating Next Right Pointers in Each Node II
- Leetcode #117 Populating Next Right Pointers in Each Node II
- LeetCode 117: Populating Next Right Pointers in Each Node II
- LeetCode 117:Populating Next Right Pointers in Each Node II
- leetcode 117 Populating Next Right Pointers in Each Node II
- Leetcode 117 Populating Next Right Pointers in Each Node II
- LeetCode 117 Populating Next Right Pointers in Each Node II
- Leetcode-117: Populating Next Right Pointers in Each Node II
- 【LeetCode】Populating Next Right Pointers in Each Node Populating Next Right Pointers in Each Node II
- 遍历 Populating Next Right Pointers in Each Node II
- HDU 1237 简单计算器(栈的应用)
- 洛谷 1041
- ubuntu配置jdk环境
- android studio关于sharedPreferences的数据存储
- 第八周OJ4小球自由下落
- LeetCode 117 Populating Next Right Pointers in Each Node II (链表 层次遍历 推荐)
- JSON格式数据从servlet传输至前台具体方法
- 【fzyzoj1578】数列分段
- 87. Scramble String
- java--jstl小结(MVC框架2)
- SAP(成都站)面试经验
- spring+dubbo+zookeeper整合
- 在固定宽度和高度的a标签中使文字居中和
- Linux标准IO编程