[LeetCode]117. 填充每个节点的下一个右侧节点指针 II(java实现)
1. 题目
2. 读题(需要重点注意的东西)
思路():
本题与[LeetCode]116. 填充每个节点的下一个右侧节点指针(java实现)的不同之处在于,本题给出的二叉树不一定是一颗完美二叉树。
我们需要在每一层用两个指针维护当前层的链表信息
具体思路如下:
-
用head指向第二层的第一个节点,tail指向第二层的最后一个节点,遍历根节点,依次将根节点的左右儿子插入下一层链表,即 2 - > 3 ;
-
用head指向第三层的第一个节点,tail指向第三层的最后一个节点,从左到右遍历第二层,依次将第二层的的子节点插入下一层链表,即 4 -> 5 -> 7
-
按上述方法,遍历到叶节点层,算法结束
3. 解法
---------------------------------------------------解法---------------------------------------------------:
/*
// 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) {
Node dummy = root;
while(root != null){
// 用head.next存储下一层的头结点
// 虚拟头结点head
Node head = new Node(0);
Node tail = head;
// 遍历当前层,维护下一层的链表
for(Node p = root; p != null;p = p.next){
if(p.left != null){
tail.next = p.left;
tail = tail.next;
}
if(p.right != null){
tail.next = p.right;
tail = tail.next;
}
}
root = head.next;
}
return dummy;
}
}
可能存在的问题: