填充每个节点的下一个右侧节点指针
题目形容:给定一个 完满二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
<code class="c">struct Node { int val; Node *left; Node *right; Node *next; }填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
示例阐明请见LeetCode官网。
起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
解法一:层序遍历
- 首先,如果root为空或者左右子节点都为空,则不须要解决next指针,间接返回root。
- 否则,当二叉树不只有一个节点时,利用队列对二叉树进行层序遍历记录二叉树每一层的节点,而后按程序解决以后层每一个节点的next指针。因为处理过程中所有的节点程序并没有进行扭转,所以最初返回root。
<code class="java">import com.kaesar.leetcode.Node; import java.util.LinkedList; import java.util.Queue; public class LeetCode_116 { public static Node connect(Node root) { // 如果root为空或者左右节点都为空,不须要解决,间接返回root if (root == null) { return root; } if (root.left == null && root.right == null) { return root; } // 利用队列记录每层的节点 Queue<Node> nodes = new LinkedList<>(); nodes.add(root); while (!nodes.isEmpty()) { int count = nodes.size(); Node last = nodes.poll(); if (last.left != null) { nodes.add(last.left); } if (last.right != null) { nodes.add(last.right); } count--; // 解决每层的节点的next指针 while (count > 0) { Node curNode = nodes.poll(); if (curNode.left != null) { nodes.add(curNode.left); } if (curNode.right != null) { nodes.add(curNode.right); } last.next = curNode; last = curNode; count--; } } return root; } public static void main(String[] args) { // 测试用例 Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); // 解决之前 root.print(); connect(root); System.out.println(); // 解决之后 root.print(); } }
【每日寄语】 好好学习,天天向上。