剑指 Offer II 043. 往完全二叉树添加节点

116 阅读1分钟

剑指 Offer II 043. 往完全二叉树添加节点

已知完全二叉树

[1,2,3,4,5,6],插入7,再插入8,插入7返回3,插入8返回了4

image.png

思路:

  • 深度遍历完全二叉树,遇到没有左右子节点的,放入栈中
  • 在插入时候,按照栈的顺序依次插入

代码实现

var CBTInserter = function (root) {
  this.arr = [];
  this.root = root;
  this.arr.push(root);
  while (this.arr[0] && this.arr[0].left && this.arr[0].right) {
    var node = this.arr.shift();
    this.arr.push(node.left);
    this.arr.push(node.right);
  }
};
CBTInserter.prototype.insert = function (v) {
  var parent = this.arr[0];
  var node = new TreeNode(v);
  if (parent.left == null) {
    parent.left = node;
  } else {
    parent.right = node;
    this.arr.shift();
    this.arr.push(parent.left);
    this.arr.push(parent.right);
  }
  return parent.val;
};
CBTInserter.prototype.get_root = function () {
  return this.root;
};


代码调试

var obj = {
  val: 1,
  left: {
    val: 2,
    left: {
      val: 4,
      left: null,
      right: null,
    },
    right: {
      val: 5,
      left: null,
      right: null,
    },
  },
  right: {
    val: 3,
    left: {
      val: 6,
      left: null,
      right: null,
    },
    right: null,
  },
};