第二十三天|669. 修剪二叉搜索树
669_关键字:搜索二叉树,剪枝
669_题目链接
代码实现:
package LeetCode;
import com.sun.scenario.effect.Brightpass;
import java.util.HashMap;
import java.util.Map;
public class YangSibo_669 {
public static void main (String args []) {
String values [] = {"3","0","4",null,"2",null,null,null,null,"1"};
Map<Integer,TreeNode> maps = new HashMap<>();
int length = values.length;
Boolean falgs [] = new Boolean[length];
for (int i = 0; i < length; i++){
if(values[i] == null ) {
continue;
}
if(!maps.containsKey(i)){
TreeNode tmp = new TreeNode(Integer.parseInt(values[i]));
maps.put(i,tmp);
}
if( ((2 * i + 1) < length) && values[2 * i + 1] != null) {
if(!maps.containsKey(2 * i + 1)){
TreeNode tmpleft = new TreeNode(Integer.parseInt(values[2 * i + 1]));
maps.put(2 * i + 1,tmpleft);
}
maps.get(i).left = maps.get(2 * i + 1);
}
if( ((2 * i + 2) < length) && values[2 * i + 2] != null) {
if(!maps.containsKey(2 * i + 2) ){
TreeNode tmpright = new TreeNode(Integer.parseInt(values[2 * i + 2]));
maps.put(2 * i + 2,tmpright);
}
maps.get(i).right = maps.get(2 * i + 2);
}
}
TreeNode root = maps.get(0);
YangSibo_669_1 demo = new YangSibo_669_1();
TreeNode result = demo.trimBST(root,1,3);
System.out.println(result.val);
}
}
class YangSibo_669_1 {
public TreeNode trimBST(TreeNode root, int low, int high) {
if( root == null) return null;
if( root.val < low) {
TreeNode left = trimBST(root.right,low,high);
return left;
}
if(root.val > high){
TreeNode right = trimBST(root.left,low, high);
return right;
}
root.left = trimBST(root.left,low,high);
root.right = trimBST(root.right,low,high);
return root;
}
}
解题注意事项
1、二次递归,第一次递归找剪枝后剩下节点
2、第二次递归是把用找到得值替换被剪掉的节点
3、明确剪枝后的排序大小,抓住搜索树的特性