填充每个节点的下一个右侧节点指针 II

题目描述:给定一个二叉树:

填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。

初始状态下,所有 next 指针都被设置为 NULL。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  1. struct Node {
  2. int val;
  3. Node *left;
  4. Node *right;
  5. Node *next;
  6. }

解法一:层序遍历

求解过程和 LeetCode-116-填充每个节点的下一个右侧节点指针 这道题完全一样,现在想想,116题中提到完美二叉树,应该使用完美二叉树的一些性质有更优的解法,而当前的解法是通用的二叉树的解法。

  • 首先,如果root为空或者左右子节点都为空,则不需要处理next指针,直接返回root。
  • 否则,当二叉树不只有一个节点时,利用队列对二叉树进行层序遍历记录二叉树每一层的节点,然后按顺序处理当前层每一个节点的next指针。由于处理过程中所有的节点顺序并没有进行改变,所以最后返回root。
  1. import com.kaesar.leetcode.Node;
  2. import java.util.LinkedList;
  3. import java.util.Queue;
  4. public class LeetCode_117 {
  5. /**
  6. * 处理方式同 LeetCode-116-填充每个节点的下一个右侧节点指针
  7. * @param root
  8. * @return
  9. */
  10. public static Node connect(Node root) {
  11. // 如果root为空或者左右节点都为空,不需要处理,直接返回root
  12. if (root == null) {
  13. return root;
  14. }
  15. if (root.left == null && root.right == null) {
  16. return root;
  17. }
  18. // 利用队列记录每层的节点
  19. Queue<Node> nodes = new LinkedList<>();
  20. nodes.add(root);
  21. while (!nodes.isEmpty()) {
  22. int count = nodes.size();
  23. Node last = nodes.poll();
  24. if (last.left != null) {
  25. nodes.add(last.left);
  26. }
  27. if (last.right != null) {
  28. nodes.add(last.right);
  29. }
  30. count--;
  31. // 处理每层的节点的next指针
  32. while (count > 0) {
  33. Node curNode = nodes.poll();
  34. if (curNode.left != null) {
  35. nodes.add(curNode.left);
  36. }
  37. if (curNode.right != null) {
  38. nodes.add(curNode.right);
  39. }
  40. last.next = curNode;
  41. last = curNode;
  42. count--;
  43. }
  44. }
  45. return root;
  46. }
  47. public static void main(String[] args) {
  48. Node root = new Node(1);
  49. root.left = new Node(2);
  50. root.right = new Node(3);
  51. root.print();
  52. connect(root);
  53. System.out.println();
  54. root.print();
  55. }
  56. }

【每日寄语】 逃避压力是没有用的,只会让压力更嚣张,勇敢地去面对。