814. 二叉树剪枝
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var pruneTree = function(root) {
// const dfs = (root) => {
// if (root == null) return 0;
// const l = dfs(root.left);
// const r = dfs(root.right);
// if (l == 0) root.left = null;
// if (r == 0) root.right = null;
// return root.val + l + r;
// }
// let ans = new TreeNode(-1);
// ans.left = root;
// dfs(ans);
// return ans.left;
const dfs = (node) => {
if (!node) return 0;
const l = dfs(node.left);
const r = dfs(node.right);
if (l == 0) node.left = null;
if (r == 0) node.right = null;
return node.val + l + r;
}
let res = new TreeNode(-1);
res.left = root;
dfs(res);
return res.left;
};
669. 修剪二叉搜索树
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} low
* @param {number} high
* @return {TreeNode}
*/
var trimBST = function(root, low, high) {
if (!root) return null;
if (root.val < low) {
return trimBST(root.right, low, high);
}
if (root.val > high) {
return trimBST(root.left, low, high);
}
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
};
1325. 删除给定值的叶子节点
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} target
* @return {TreeNode}
*/
/*
删除指定值的叶子节点,其实就是遍历所有的叶子节点,然后判断是否需要删除;删除叶子节点也很简单,return null 让父节点接收即可。
难点在于他这个删除操作是循环的,一直删到叶子结点不存在 target 为止
一个节点要在后序位置接收左右子树的返回值,才能知道自己的叶子节点是否都被删掉了,以此判断自己是不是变成了叶子节点。
*/
var removeLeafNodes = function(root, target) {
if (!root) return null;
root.left = removeLeafNodes(root.left, target);
root.right = removeLeafNodes(root.right, target);
if (root.val === target && root.left == null && root.right == null) {
return null;
}
return root;
};