235. 二叉搜索树的最近公共祖先
解题思路
后序遍历
代码实现
var lowestCommonAncestor = function(root, p, q) {
var dfs = function(root,p,q){
if(!root) return root;
if(p ===root || root===q) return root;
var left = dfs(root.left,p,q);
var right =dfs(root.right,p,q);
if(right && left) return root;
if(!right && left) return left;
if(!left && right) return right;
if(!right && !left) return null;
}
return dfs(root,p,q);
};
701.二叉搜索树中的插入操作
解题思路
二叉搜索树的插入,最后必定会插入叶子结点
代码实现
var insertIntoBST = function(root, val) {
var dfs = function(root,val){
if(root == null){
var node = new TreeNode(val);
return node;
}
if(root.val>val){
root.left = dfs(root.left,val);
}
if(root.val<val){
root.right = dfs(root.right,val);
}
return root;
}
return dfs(root,val);
};
450.删除二叉搜索树中的节点
解题思路
有以下五种情况:
-
第一种情况:没找到删除的节点,遍历到空节点直接返回了
-
找到删除的节点
- 第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
- 第三种情况:删除节点的左孩子为空,右孩子不为空,删除节点,右孩子补位,返回右孩子为根节点
- 第四种情况:删除节点的右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
- 第五种情况:左右孩子节点都不为空,则将删除节点的左子树头结点(左孩子)放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。
第五种情况有点难以理解,看下面动画:
代码实现
var deleteNode = function(root, key) {
if(root == null) return null;
if(root!==null && root.val ===key){
if(root.left !==null && root.right == null){
return root.left;
}
if(root.right !=null && root.left == null){
return root.right;
}
if(root.right == null && root.left == null){
return null;
}
if(root.left !==null && root.right !== null){
var cur = root.right
while(cur.left !== null){
cur = cur.left;
}
cur.left = root.left;
return root.right;
}
}
root.left = deleteNode(root.left,key);
root.right = deleteNode(root.right,key);
return root;
};