二叉树part08
前序,利用二叉搜索的特性
/**
* 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;
//如果等于p或q就返回
if(root === p || root === q) return root;
if((p.val < root.val && q.val > root.val) || (p.val > root.val && q.val < root.val)) return root;
if(p.val > root.val && q.val > root.val){
return lowestCommonAncestor(root.right, p, q);
}else if(p.val < root.val && q.val < root.val){
return lowestCommonAncestor(root.left, p, q)
}
};
/**
* 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){
//找到插入点
let node = new TreeNode(val);
return node;
}
if(root.val > val){
root.left = insertIntoBST(root.left, val);
}else if(root.val < val){
root.right = insertIntoBST(root.right, val);
}
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) {
//如果删除节点5
//有三种情况
//1.两个孩子都有 :让较小的孩子成为较大的孩子的孩子
//假设right孩子大
//操作root.left.right = root.right
//只有一个孩子,让孩子替代自己
};
function deleteNode(node, key){
if(!node) return null;
deleteNode()
}