leetcode第116题填充每个节点的下一个右侧节点指针

70 阅读1分钟

题目 给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

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

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

题目链接

我的JavaScript解法

/**
 * // Definition for a Node.
 * function Node(val, left, right, next) {
 *    this.val = val === undefined ? null : val;
 *    this.left = left === undefined ? null : left;
 *    this.right = right === undefined ? null : right;
 *    this.next = next === undefined ? null : next;
 * };
 */

/**
 * @param {Node} root
 * @return {Node}
 */
var connect = function(root) {
  if(root == null)
    return root;

  const stack = [];
  stack.push(root);
  while(stack.length) {
    let size = stack.length;
    for(let i = 0; i < size; i++) {
      let node = stack.shift();
      if (i < size - 1) {
        node.next = stack[0];
      }

      if(node.left != null)
        stack.push(node.left);
      if(node.right != null)
        stack.push(node.right);
    }
  };

  return root;
};

解析: 二叉树的层序遍历

  • 时间复杂度 O(n)O(n)
  • 空间复杂度 O(n)O(n)