669. Trim a Binary Search Tree
给一颗bst和一个范围,将bst中所有不在范围内的结点删除。
public TreeNode trimBST(TreeNode root, int L, int R) {
if (root == null) return null;
if (root.val <= R && root.val >= L) {
root.left = trimBST(root.left, L, R);
root.right = trimBST(root.right, L, R);
} else if (root.val > R) {
root = trimBST(root.left, L, R);
} else {
root = trimBST(root.right, L, R);
}
return root;
}
814. Binary Tree Pruning
一个二叉树所有结点是0或1,将其中子树上结点都是0的子树删除。
其实不用两个递归就可以做出来,但我没有想到,做法是从叶子结点进行修建,如果是0就删除:
public TreeNode pruneTree(TreeNode root) {
if (root == null) return root;
if (isContain1(root.left)) {
root.left = null;
} else {
root.left = pruneTree(root.left);
}
if (isContain1(root.right))
root.right = null;
else
root.right = pruneTree(root.right);
return root;
}
//if tree contain 1, return false
public boolean isContain1(TreeNode root) {
if (root == null) return true;
if (root.val == 1) return false;
return isContain1(root.left) && isContain1(root.right);
}
1325. Delete Leaves With a Given Value
给一个二叉树和一个target,删除树中所有在叶子结点中等于target的结点,如果一个非叶子结点也等于target,再修建后它变成了叶子结点,那么它也要被删除。
递归法,从叶子结点开始删除就行,在回溯到上一个结点时如果它变成了叶子结点且等于target就也会被删除:
public TreeNode removeLeafNodes(TreeNode root, int target) {
if (root == null) return null;
root.left = removeLeafNodes(root.left, target);
root.right = removeLeafNodes(root.right, target);
if (root.left == null && root.right == null && root.val == target) {
return null;
}
return root;
}