其实就是个二叉树的层次遍历
class Solution {
public void connect(TreeLinkNode root) {
if (root == null) return;
LinkedList<TreeLinkNode> queue = new LinkedList<>();
queue.offer(root);
TreeLinkNode flag = root;
TreeLinkNode last = null;
while (!queue.isEmpty()) {
TreeLinkNode nowNode = queue.poll();
if (last != null) {
last.next = nowNode;
}
if (nowNode.left != null) queue.add(nowNode.left);
if (nowNode.right != null) queue.add(nowNode.right);
last = nowNode;
if (flag == nowNode) {
nowNode.next = null;
flag = queue.peekLast();
last = null;
}
}
}
}
原文地址:https://www.cnblogs.com/acbingo/p/9919419.html
时间: 2024-11-17 04:47:42