[LeetCode]117. Populating Next Right Pointers in Each Node II
来源:互联网 发布:词语意思大全软件 编辑:程序博客网 时间:2024/09/21 06:33
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. * 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; int thislevel = 1; int nextlevel = 0; LinkedList<TreeLinkNode> q = new LinkedList<TreeLinkNode>(); q.add(root); while(q.isEmpty() == false) { while(thislevel > 0) { TreeLinkNode temp = q.poll(); thislevel--; if (thislevel == 0) temp.next = null; else temp.next = q.peek(); if(temp.left != null) { nextlevel++; q.offer(temp.left); } if(temp.right != null) { nextlevel++; q.offer(temp.right); } } thislevel = nextlevel; nextlevel = 0; } }}
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
- 从零开始的Android新项目1 - 架构搭建篇
- 使用 Nginx 构建一个“高”可用的 PHP 集群
- 有近一年没有写blog了,值此技术飞速发展更新的年代,是时候对自己的技术体系做全面的更新
- python常用模块
- tomcat部署失败问题
- [LeetCode]117. Populating Next Right Pointers in Each Node II
- [期望DP] BZOJ4008 [HNOI2015]亚瑟王
- android 禁止通知栏下拉
- 美团在Redis上踩过的一些坑-1.客户端周期性出现connect timeout
- BZOJ 100题 留念
- 分享一个仿就看天气应用源码
- Java Collection List Set Map 的区别
- mysql显示中文乱码
- IE8的select