Populating Next Right Pointers in Each Node II
来源:互联网 发布:吉他读谱软件 编辑:程序博客网 时间:2024/05/29 15:24
Q:
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
Solution:
/** * 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; Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>(); queue.offer(root); while (!queue.isEmpty()) { Queue<TreeLinkNode> level = new LinkedList<TreeLinkNode>(); TreeLinkNode first = queue.poll(); if(first.left != null) level.offer(first.left); if(first.right != null) level.offer(first.right); while (!queue.isEmpty()) { TreeLinkNode second = queue.poll(); if(second.left != null) level.offer(second.left); if(second.right != null) level.offer(second.right); first.next = second; first = second; } first.next = null; queue = new LinkedList<TreeLinkNode>(level); } }}
0 0
- Populating Next Right Pointers in Each Node、Populating Next Right Pointers in Each Node II
- 【LeetCode】Populating Next Right Pointers in Each Node Populating Next Right Pointers in Each Node II
- LeetCode Populating Next Right Pointers in Each Node II
- [Leetcode] Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node II
- leetcode 79: Populating Next Right Pointers in Each Node II
- [Leetcode] Populating Next Right Pointers in Each Node ii
- leetcode Populating Next Right Pointers in Each Node II
- 【leetcode】Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- [Leetcode]Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node (I & II)
- Populating Next Right Pointers in Each Node II
- java设计模式示例
- Android开发小问题集
- JS 常用函数 去空格、去重复元素 jquery去空格 1410231
- ubuntu安装ftp服务器
- Azure网站上的PHP — 架构
- Populating Next Right Pointers in Each Node II
- JQuery replace字符串替换
- TMS320F28335项目开发记录9_28335之中断系统
- Android ActionBar完全解析,使用官方推荐的最佳导航栏(下)
- c#流总结
- Azure网站上的PHP — 配置
- 工业机器人相关知识
- Openstack部署总结之:部署过程中“Error: Local ip for ovs agent must be set when tunneling is enabled”的问题
- ubuntu下mysql的'Access denied for user 'root'@'localhost