LeetCode 117. 填充每个节点的下一个右侧节点指针 II
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
进阶:
你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
例如:
题解:
方法一:与上一篇文章中-LeetCode 116-的方法一样,可以通过使用队列进行层次遍历的方法求解。这样时间复杂度为O(n),空间复杂度为O(n)。
方法二:与-LeetCode 116-的方法一样同样,利用已经建立好的next的指针,在第N层为N + 1层建立next指针。只需要找到每层的最左侧节点。
/*
// 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 {
private Node last = null; //在建立一层的连接时保存最后一个建立连接的节点。
private Node nextStart = null; //每一层的最左侧节点
public Node connect(Node root) {
if(root == null)
return null;
Node start = root;
while(start != null){
last = null;
nextStart = null;
for(Node p = start; p != null; p = p.next){
if(p.left != null)
handle(p.left);
if(p.right != null)
handle(p.right);
}
start = nextStart;
}
return root;
}
public void handle(Node p){
if(last != null)
last.next = p;
if(nextStart == null)
nextStart = p;
last = p;
}
}
题目链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii
题解参考:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/solution/tian-chong-mei-ge-jie-dian-de-xia-yi-ge-you-ce-15/