450. 删除二叉搜索树中的节点
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
root = delete(root, key);
return root;
}
public TreeNode delete(TreeNode root, int key){
//首先判断root是否为空,为空后续操作会报异常
if(root == null)
return null;
//前序遍历,相等则处理当前节点,不相等则不处理当前节点
if(root.val == key){
if(root.left == null && root.right == null)
return null;
else if(root.left == null && root.right != null)
return root.right;
else if(root.right == null && root.left != null)
return root.left;
else if(root.left != null && root.right != null){
TreeNode node = root.right;
while(node.left != null){
node = node.left;
}
node.left = root.left;
return root.right;
}
}
//处理左右节点
if(key < root.val)
root.left = delete(root.left, key);
if(key > root.val)
root.right = delete(root.right, key);
//处理完后,返回当前节点
return root;
}
}
669. 修剪二叉搜索树
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
root = traversal(root, low, high);
return root;
}
public TreeNode traversal(TreeNode root, int low, int high){
if(root == null)
return null;
root.left = traversal(root.left, low, high);
root.right = traversal(root.right, low, high);
if(root.val > high || root.val < low){
if(root.left == null && root.right == null)
return null;
else if(root.left != null && root.right == null)
return root.left;
else if(root.left == null && root.right != null)
return root.right;
else if(root.left != null && root.right != null){
TreeNode node = root.right;
while(node.left != null){
node = node.left;
}
node.left = root.left;
return root.right;
}
}
//二叉树真是太tm神奇了,和《删除节点》一样的代码,前序遍历只处理一个节点就返回,改为后续遍历之后就可以处理全局(因为后续遍历是天然回溯,是自底向上;前序是,自顶向下)
//这种方法,不仅仅适用于二叉搜索树,具有普适性
return root;
}
}
//这种方法仅仅适用于
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
root = traversal(root, low, high);
return root;
}
public TreeNode traversal(TreeNode root, int low, int high){
if(root == null)
return null;
//前序遍历
if(root.val < low)
return traversal(root.right, low, high);
if(root.val > high)
return traversal(root.left, low, high);
//开始处理左右节点
root.left = traversal(root.left, low, high);
root.right = traversal(root.right, low, high);
return root;
}
}