可以用递归返回当前的节点,然后在上一层用root.left 和root.right接住,就可以实现了父子节点的链接了!
235. 二叉搜索树的最近公共祖先
因为是二叉搜索树,并且要找祖先,向下找就可以了,不涉及遍历顺序。那么只要从上到下去遍历,遇到 cur节点是数值在[p, q]区间中则一定可以说明该节点cur就是q 和 p的最近公共祖先。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function (root, p, q) {
if (root === null) return null;
if (root.val > p.val && root.val > q.val) {
return root.left = lowestCommonAncestor(root.left, p, q);
}
if (root.val < p.val && root.val < q.val) {
return root.right = lowestCommonAncestor(root.right, q, p);
}
return root;
}
701. 二叉搜索树中的插入操作
只要遍历二叉搜索树,找到空节点 插入元素就可以了,在叶子节点上插入。
终止条件:遍历到节点为null时,就是要插入节点的位置了,并把插入的节点返回。
每层逻辑:如何通过递归函数返回值完成了新加入节点的父子关系赋值操作了,下一层将加入节点返回,本层用root->left或者root->right将其接住。
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} val
* @return {TreeNode}
*/
var insertIntoBST = function (root, val) {
if (root === null) {
return new TreeNode(val);
}
if (val < root.val) {
root.left = insertIntoBST(root.left, val);
}
if (val > root.val) {
root.right = insertIntoBST(root.right, val);
}
return root;
};
450. 删除二叉搜索树中的节点
递归三部曲:
- 通过递归返回值删除节点。
- 遇到空返回,其实这也说明没找到删除的节点,遍历到空节点直接返回了。
- 五种情况:
- 第一种情况:没找到删除的节点,遍历到空节点直接返回了
- 第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
- 第三种情况:删除节点的左孩子为空,右孩子不为空,删除节点,右孩子补位,返回右孩子为根节点
- 第四种情况:删除节点的右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
- 第五种情况:左右孩子节点都不为空,则将删除节点的左子树头结点(左孩子)放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} key
* @return {TreeNode}
*/
var deleteNode = function (root, key) {
if (!root) return null;
// 终止条件
if (root.val === key) {
// 叶子节点
if (root.left === null && root.right === null) {
return null;
}
// 有一个叶子节点不存在
if (root.left === null && root.right !== null) {
return root.right;
} else if (root.left !== null && root.right === null) {
return root.left;
}
// 左右节点都存在呢
let cur = root.right;
while (cur.left !== null) {
cur = cur.left;
}
cur.left = root.left;
return root.right;
}
// 左
if (key > root.val) {
root.right = deleteNode(root.right, key);
return root;
}
// 右
else if (key < root.val) {
root.left = deleteNode(root.left, key);
return root;
}
return root;
};