填充每个节点的下一个右侧节点指针 II
题目形容:给定一个二叉树:
struct Node { int val; Node *left; Node *right; Node *next;}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
示例阐明请见LeetCode官网。
起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
解法一:层序遍历
求解过程和 LeetCode-116-填充每个节点的下一个右侧节点指针 这道题齐全一样,当初想想,116题中提到完满二叉树,应该应用完满二叉树的一些性质有更优的解法,而以后的解法是通用的二叉树的解法。
- 首先,如果root为空或者左右子节点都为空,则不须要解决next指针,间接返回root。
- 否则,当二叉树不只有一个节点时,利用队列对二叉树进行层序遍历记录二叉树每一层的节点,而后按程序解决以后层每一个节点的next指针。因为处理过程中所有的节点程序并没有进行扭转,所以最初返回root。
import com.kaesar.leetcode.Node;import java.util.LinkedList;import java.util.Queue;public class LeetCode_117 { /** * 解决形式同 LeetCode-116-填充每个节点的下一个右侧节点指针 * @param root * @return */ 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(); }}
【每日寄语】 回避压力是没有用的,只会让压力更嚣张,怯懦地去面对。