一、二叉搜索树的最近公共祖先
利用二叉搜索树的有序特性特性
递归法
/**
* 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) {
return null
}
if(root.val > p.val && root.val > q.val) {
return lowestCommonAncestor(root.left, p, q)
} else if(root.val < p.val && root.val < q.val) {
return lowestCommonAncestor(root.right, p, q)
} else {
return root
}
};
迭代法
var lowestCommonAncestor = function (root, p, q) {
if (!root) {
return null
}
while (root) {
if (root.val > p.val && root.val > q.val) {
root = root.left
} else if (root.val < p.val && root.val < q.val) {
root = root.right
} else {
return root
}
}
return 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} val
* @return {TreeNode}
*/
var insertIntoBST = function (root, val) {
if (!root) {
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
};
不带返回值的递归
var insertIntoBST = function (root, val) {
let parent
if(!root) {
return new TreeNode(val)
}
function dfs(root) {
if (!root) {
let node = new TreeNode(val)
if(node.val > parent.val) {
parent.right = node
}
if(node.val < parent.val) {
parent.left = node
}
return
}
parent = root
if (val < root.val) {
dfs(root.left)
}
if (val > root.val) {
dfs(root.right)
}
}
dfs(root)
return root
};
三、删除二叉搜索树中的节点
要注意节点删除的各种情况
递归法
/**
* 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 root
}
if(root.val > key) {
root.left = deleteNode(root.left, key)
} else if(root.val < key) {
root.right = deleteNode(root.right, key)
} else {
if(!root.left && !root.right) {
return null
} else if(!root.left) {
return root.right
} else if(!root.right) {
return root.left
} else {
let cur = root.right
while(cur.left) {
cur = cur.left
}
cur.left = root.left
return root.right
}
}
return root
};
迭代法
var deleteNode = function (root, key) {
if (!root) {
return root
}
let cur = root
let pre
while (cur) {
if (cur.val > key) {
pre = cur
cur = cur.left
} else if (cur.val < key) {
pre = cur
cur = cur.right
} else {
if (!pre) {
return deleteOneNode(cur)
} else {
if (pre.left === cur) {
pre.left = deleteOneNode(cur)
}
if (pre.right === cur) {
pre.right = deleteOneNode(cur)
}
}
return root
}
}
return root
}