给定一个二叉树
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL
。
初始状态下,所有 next 指针都被设置为 NULL
。
说明:
- 你只能使用额外常数空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
- 你可以假设它是一个完美二叉树(即所有叶子节点都在同一层,每个父节点都有两个子节点)。
示例:
给定完美二叉树,
1 / \ 2 3 / \ / \ 4 5 6 7
调用你的函数后,该完美二叉树变为:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
题目还是很简单的,因为限定了是完美二叉树
但是第一遍代码写得太冗余了,完全是靠人工强行判断,虽然通过了平台的检测,但是看着难受,想办法优化一下
import java.util.LinkedList;
import java.util.Queue;
public class RightNode {
public void connect(TreeLinkNode root){
if(root!=null){
Queue<TreeLinkNode> firstQueue=new LinkedList<>();
Queue<TreeLinkNode> secondQueue=new LinkedList<>();
firstQueue.add(root);
boolean flag=true;
while (true){
TreeLinkNode temp1;
TreeLinkNode temp2;
if(flag) {
if (firstQueue.size() == 1) {
TreeLinkNode temp=firstQueue.poll();
temp.next=null;
if(temp.right!=null) {
secondQueue.add(temp.left);
secondQueue.add(temp.right);
}
flag=false;
} else if(firstQueue.size()!=0){
temp1 = firstQueue.poll();
if(temp1.right!=null) {
secondQueue.add(temp1.left);
secondQueue.add(temp1.right);
}
temp2 = firstQueue.poll();
if(temp2.right!=null) {
secondQueue.add(temp2.left);
secondQueue.add(temp2.right);
}
temp1.next = temp2;
while (!firstQueue.isEmpty()) {
temp1 = temp2;
temp2 = firstQueue.poll();
if(temp2.right!=null) {
secondQueue.add(temp2.left);
secondQueue.add(temp2.right);
}
temp1.next = temp2;
}
temp2.next = null;
flag=false;
}else if(firstQueue.size()==0){
break;
}
}else{
if(secondQueue.size()!=0){
temp1 = secondQueue.poll();
if(temp1.right!=null) {
firstQueue.add(temp1.left);
firstQueue.add(temp1.right);
}
temp2 = secondQueue.poll();
if(temp2.right!=null) {
firstQueue.add(temp2.left);
firstQueue.add(temp2.right);
}
temp1.next = temp2;
while (!secondQueue.isEmpty()) {
temp1 = temp2;
temp2 = secondQueue.poll();
if(temp2.right!=null) {
firstQueue.add(temp2.left);
firstQueue.add(temp2.right);
}
temp1.next = temp2;
}
temp2.next = null;
flag=true;
}else if(secondQueue.size()==0){
break;
}
}
}
}
}
}
class TreeLinkNode {
int val;
TreeLinkNode left, right, next;
TreeLinkNode(int x) { val = x; }
}