tree

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值