117. 填充每个节点的下一个右侧节点指针 II
题目:
思路:
【1】利用层次遍历的思维
【1.1】利用队列进行层次遍历
【1.2】利用链表替代队列进行层次遍历(这种基于原本Node就具备链表的属性,所以只需要创建一个常量头结点辅助即可,否则需要创建一个完整的链表的话还不如使用队列)
代码展示:
//时间1 ms 击败 74.22% //内存42 MB 击败 51.78% /* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; } }; */ class Solution { public Node connect(Node root) { if (root == null) return null; LinkedList<Node> que = new LinkedList<>(); que.add(root); while (!que.isEmpty()){ int count = que.size(); Node left = null; while (count-- > 0){ Node tem = que.poll(); if (tem.left != null) que.add(tem.left); if (tem.right != null) que.add(tem.right); if (left != null){ left.next = tem; } left = tem; } } return root; } } //进阶的处理 //时间0 ms 击败 100% //内存42 MB 击败 51.42% class Solution { public Node connect(Node root) { Node cur = root; while(cur!=null){ //利用链表来替代队列 Node dummy = new Node(0); Node pre= dummy; while(cur!=null){ // 将数据塞入新的链表 if (cur.left!=null){ pre.next = cur.left; pre = pre.next; } if (cur.right!=null){ pre.next = cur.right; pre = pre.next; } cur = cur.next; } // 将新的链表赋予下一次遍历的指针 cur = dummy.next; } return root; } }