代码随想录的第十九天(二叉树)
235. 二叉搜索树的最近公共祖先
var lowestCommonAncestor = function(root, p, q) {
if (root === null || root === p || root === q) {
return root
}
let left =lowestCommonAncestor(root.left, p, q)
let right = lowestCommonAncestor(root.right, p, q)
if (left !== null && right !== null) {
return root
}
if (left === null) {
return right
}
return left
};
搜索普通二叉树的思路:
1、如果遍历到根节点或者是目标节点就将当前的root进行返回
2、遍历左右子树,如果左右子树都不为空,说明找到了当前最近的公共祖先元算进行返回
3、否则有一边遍历完成就去遍历另外一边
var lowestCommonAncestor = function(root, p, q) {
if(root === null) return null;
if (root.val > p.val && root.val > q.val) {
let left = lowestCommonAncestor(root.left, p ,q)
if (left !== null) return left
}
if (root.val < p.val && root.val < q.val) {
right = lowestCommonAncestor(root.right, p ,q)
if (right !== null) return right
}
return root
};
利用搜索二叉树特性:
1、公共节点肯定是在p和q之间,因为搜索二叉树是递增的,并且是唯一的
2、所以只需要去遍历左子树和右子树,找到节点返回
701. 二叉搜索树中的插入操作
var insertIntoBST = function(root, val) {
if (root === null) {
let node = new TreeNode(val)
return node
}
if (root.val > val) {
root.left = insertIntoBST(root.left, val)
}
if (root.val < val) {
root.right = insertIntoBST(root.right, val)
}
return root
};
思路:
1、二叉搜索树的特性,就是在叶子节点上去插入新增的node,当当前值大于目标val的时候,说明在左子树上;否则在右子树上
2、遍历到root为空的时候,说明到了叶子节点,此时需要返回新增的节点
3、然后在当前的节点进行拼接返回的node节点
450. 删除二叉搜索树中的节点
var deleteNode = function(root, key) {
// 没有找到节点
if (root === null) return null
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
} else {
// 找到了目标元素
// 如果目标元素是叶子节点
if (root.left === null && root.right === null) {
return null
}
// 如果目标元素左为空,右不为空(返回不为空的那边的树)
if (root.left === null && root.right !== null) {
return root.right
}
// 如果目标元素右为空,左不为空(返回不为空的那边的树)
if (root.left !== null && root.right === null) {
return root.left
}
// 如果左右子树都不为空
if (root.left !== null && root.right !== null) {
const rightNode = root.right
const minNode = getMinNode(rightNode)
root.val = minNode.val
// 删除最小值节点
root.right = deleteNode(root.right, minNode.val);
}
return root
}
};
function getMinNode (root) {
// 找到最左边的节点就是最小的节点然后进行树的拼接
while (root.left) {
root = root.left;
}
return root;
}