这道题实际上是树的层序遍历的应用,既然是遍历,就有递归和非递归两种方法。下面先来看递归的解法,由于是完全二叉树,所以若节点的左子结点存在的话,其右子节点必定存在,所以左子结点的next指针可以直接指向其右子节点,对于其右子节点的处理方法是,判断其父节点的next是否为空,若不为空,则指向其next指针指向的节点的左子结点,若为空则指向NULL,代码如下:
//solution1:递归解法
public void connect1(TreeNode root) {
if(root == null) return;
if(root.left != null) root.left.next = root.right;
if(root.right != null) root.right.next = root.next==null?root.next.left:null;
connect1(root.left);
connect1(root.right);
}
对于非递归的解法要稍微复杂一点,但也不算特别复杂,需要用到queue来辅助,由于是层序遍历,每层的节点都按顺序加入queue中,而每当从queue中取出一个元素时,将其next指针指向queue中下一个节点即可。代码如下:
//solution2:非递归,使用null来记录分层
public void connect2(TreeNode root) {
if(root == null ) return ;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
q.offer(null);
while(true) {
TreeNode cur = q.poll();
if(cur!=null) {
cur.next = q.peek();
if(cur.left!=null) q.offer(cur.left);
if(cur.right!=null) q.offer(cur.right);
}else {
if(q.size() == 0|| q.peek() == null) return;
q.offer(null);
}
}
}
上面的方法巧妙的通过给queue中添加空指针NULL来达到分层的目的,使每层的最后一个节点的next可以指向NULL,那么我们可以换一种方法来实现分层,我们对于每层的开头元素开始遍历之前,先统计一下该层的总个数,用个for循环,这样for循环结束的时候,我们就知道该层已经被遍历完了,这也是一种好办法:
//solution3:非递归,记录每层的节点个数,然后用for循环每层
public void connect3(TreeNode root) {
if(root == null) return;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()) {
int size = q.size();
for(int i = 0;i<size ;i++) {
TreeNode node = q.poll();
if(i<size-1) {
node.next = q.peek();
}
if(node.left!=null) q.offer(node.left);
if(node.right!=null) q.offer(node.right);
}
}
}
上面三种方法虽然叼,但是都不符合题意,题目中要求用O(1)的空间复杂度,所以我们来看下面这种碉堡了的方法。用两个指针start和cur,其中start标记每一层的起始节点,cur用来遍历该层的节点,设计思路之巧妙,不得不服啊:
//solution4:非递归,空间复杂度O(1)
public void connect4(TreeNode root) {
if(root == null) return ;
//start记录每层的起始节点,因为每层的起始节点一定是每层的最左节点,所以只需保存每层的最左节点即可!
TreeNode start = root;
//cur用来遍历当前层的下一层节点
TreeNode cur = null;
while(start.left!=null) {
cur = start;
while(cur != null) {
cur.left.next = cur.right;
if(cur.next!=null) {
cur.right.next = cur.next.left;
}
cur = cur.next;
}
start = start.left;
}
}
方法四不仅时间复杂度为o(1),在运行时间上也很快: