摘要:
思路:和108题类似,链表需要通过双指针寻找中间节点。 class Solution { public TreeNode sortedListToBST(ListNode head) { if (head == null) return null; if (head.next == null) re 阅读全文
摘要:
☆☆思路:BST的中序遍历时升序的,因此本题等同于根据中序遍历的序列恢复二叉搜索树。 可以选择中间数字作为二叉搜索树的根节点,这样分给左右子树的数字个数相同或只相差 1,可以使得树保持平衡。 class Solution { public TreeNode sortedArrayToBST(int[ 阅读全文
摘要:
☆☆☆思路:经典的LCA问题 class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) return null; if (p == 阅读全文
摘要:
☆☆思路:中序遍历时,判断当前节点是否大于中序遍历的前一个节点,如果大于,满足BST,继续遍历;否则返回false。 技巧点:保存前一个节点 + 中序遍历 class Solution { TreeNode pre = null; public boolean isValidBST(TreeNode 阅读全文
摘要:
class Solution { int min = Integer.MAX_VALUE; TreeNode pre = null; public int getMinimumDifference(TreeNode root) { inOrder(root); return min; } priva 阅读全文
摘要:
二分搜索树: 1. 每个节点的键值大于左孩子; 2. 每个节点的键值小于右孩子; 3. 以左右孩子为根的子树仍为二分搜索树。 ☆☆思路:中序遍历,计算相邻数的差值 class Solution { int min = Integer.MAX_VALUE; TreeNode pre = null; / 阅读全文
摘要:
☆☆ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { /** * 方法1:递归 */ if (p.val < root.val && q.val < root 阅读全文
摘要:
【举一反三】:在二叉树中找到累加和为指定值的最长路径长度 左神P115 ☆☆☆☆思路1:双重递归,第一个递归用来遍历这些节点,这二个递归用来处理这些节点,进行dfs。 思路1的缺点是存在大量重复计算,时间效率差 ☆☆☆☆☆思路2:前缀和 递归回溯。 时间复杂度为O(n),空间复杂度为O(n) 代码1 阅读全文