leetcode-117. Populating Next Right Pointers in Each Node II
来源:互联网 发布:windows密码 编辑:程序博客网 时间:2024/05/22 08:04
leetcode-117. 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,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
和上一题不同。这里结构不是固定的了所以需要使用队列去保存当前的信息。而且有很多需要注意的小细节。
首先从思路上来说还是用FIFO的队列,并且每个循环体内都替换一次。直到到最后一行队列为空则终止循环。
外层循环每一层循环异常。内层循环针对当前对立的每个节点。
/** * 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 ; LinkedList<TreeLinkNode> list = new LinkedList<TreeLinkNode>(); list.add(root); while(list.size()!=0){ LinkedList<TreeLinkNode> replace = new LinkedList<TreeLinkNode>(); TreeLinkNode pre = list.remove(); if(pre.left!=null) replace.add(pre.left); if(pre.right!=null) replace.add(pre.right); TreeLinkNode cur = null; while(list.size()!=0){ cur = list.remove(); if(cur!=null && cur.left!=null) replace.add(cur.left); if(cur!=null && cur.right!=null) replace.add(cur.right); pre.next = cur; if(cur!=null) pre = cur; } if(replace.size()!=0) replace.add(null); list = replace; } }}
0 0
- 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 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] 117. Populating Next Right Pointers in Each Node II
- LeetCode#117. Populating Next Right Pointers in Each Node II
- 数字三角形问题
- WMI 定时启动木马
- Android 自定义View合集
- Android Studio 常见问题
- STM32之待机唤醒
- leetcode-117. Populating Next Right Pointers in Each Node II
- 7.imshow显示问题
- greendao的使用
- vue(一)——vue-cli的搭建
- 11.标识符_unicode和GBK_各种字符集的关系
- aaa
- 字符串使用下标的方式访问其中的元素不兼容ie7和ie6
- Java编程题自动评分技术的研究与实现(二)
- 一个android码农的2016年总结