669. 修剪二叉搜索树
https://leetcode-cn.com/problems/trim-a-binary-search-tree/
这个题和上一个二叉搜索树的题好相似呀,都可以使用递归处理,可能二叉搜索树的前序本身是一个升序的系列,正好对应了分治算法。
//递归方程 当root在区间内,则对左树,右树进行整改后,返回root,
// 当root<low,则整改右树,并返回右树中的结果,当右树也为null,停止
// 当root>high,则整改左树,并返回左树中的结果,当左树也为null,停止
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return null;
}
if (root.val >= low && root.val <= high) {
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
} else if (root.val < low) {
root.right = trimBST(root.right, low, high);
return root.right;
} else {
root.left = trimBST(root.left, low, high);
return root.left;
}
}
24. 两两交换链表中的节点
这个大神的解析十分清晰
有两个困难题,原子数量和最大路径和,一个可以用栈解决,一个和二叉树相关,学习数据结构后学习。