给定一个二叉树

    struct Node {
    int val;
    Node left;
    Node
    right;
    Node *next;
    }
    填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。

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

    进阶:

    你只能使用常量级额外空间。
    使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。

    示例:
    image.png
    输入:root = [1,2,3,4,5,null,7]
    输出:[1,#,2,3,#,4,5,7,#]
    解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化输出按层序遍历顺序(由 next 指针连接),’#’ 表示每层的末尾。

    1. /**
    2. * // Definition for a Node.
    3. * function Node(val, left, right, next) {
    4. * this.val = val === undefined ? null : val;
    5. * this.left = left === undefined ? null : left;
    6. * this.right = right === undefined ? null : right;
    7. * this.next = next === undefined ? null : next;
    8. * };
    9. */
    10. /**
    11. * @param {Node} root
    12. * @return {Node}
    13. */
    14. var connect = function (root) {
    15. // 因为不是完成二叉树,所以不能使用递归,这里用bfs
    16. if (!root) return null;
    17. let q = [root];
    18. while (q.length) {
    19. const n = q.length;
    20. let last = null;
    21. for (let i = 1; i <= n; ++i) {
    22. let f = q.shift();
    23. if (f.left !== null) {
    24. q.push(f.left);
    25. }
    26. if (f.right !== null) {
    27. q.push(f.right);
    28. }
    29. if (i !== 1) {
    30. last.next = f;
    31. }
    32. last = f;
    33. }
    34. }
    35. return root;
    36. };

    image.png