上一页 1 2 3 4 5 6 ··· 15 下一页
摘要: 利用BST有序的特点即可。 class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q 阅读全文
posted @ 2022-03-06 16:54 明卿册 阅读(13) 评论(0) 推荐(0) 编辑
摘要: 拿到这个题目首先想到的就是希望能够自底向上, 应该使用回溯,回溯是天然的自底向上。 后序遍历就是天然的回溯,最先处理的一定是叶子节点。 那么要走递归三部曲: 确定返回值和参数 确定终止条件 循环体 确定返回值和参数 其实这道题最基本的想法应该是用boolean来表示root中能否找到p和q,不过可以 阅读全文
posted @ 2022-03-06 16:30 明卿册 阅读(15) 评论(0) 推荐(0) 编辑
摘要: 利用BST的中序遍历是有序的这个特点即可,再使用树的双指针即可。 难点在于先处理time,再使用time去更新list。 然后双指针的初始化问题是双指针中经常遇到的问题。 class Solution { private TreeNode pre; private int maxTime = 0, 阅读全文
posted @ 2022-03-06 15:53 明卿册 阅读(22) 评论(0) 推荐(0) 编辑
摘要: 显然二叉搜索树中两两间距最小的点一定是对该树进行中序遍历得到的: class Solution { private int ans = Integer.MAX_VALUE; private TreeNode pre = null; public int getMinimumDifference(Tr 阅读全文
posted @ 2022-03-06 15:33 明卿册 阅读(15) 评论(0) 推荐(0) 编辑
摘要: 这道题有个大陷阱就是,不能单纯比较根节点和左右两个子节点的关系。 所以需要中序遍历,让每个子节点和它的上一个节点进行对比。 class Solution { TreeNode pre = null; public boolean isValidBST(TreeNode root) { if(root 阅读全文
posted @ 2022-03-06 15:19 明卿册 阅读(22) 评论(0) 推荐(0) 编辑
摘要: 利用二叉搜索树的特点即可: class Solution { public TreeNode searchBST(TreeNode root, int val) { if(root==null) return null; if(root.left == null && root.right == n 阅读全文
posted @ 2022-03-06 14:59 明卿册 阅读(10) 评论(0) 推荐(0) 编辑
摘要: 几乎是最简单的递归题了。 class Solution { public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { if(root1 == null && root2 == null) return null; else if(roo 阅读全文
posted @ 2022-03-06 14:44 明卿册 阅读(8) 评论(0) 推荐(0) 编辑
摘要: 题目链接:https://leetcode-cn.com/problems/maximum-binary-tree/ 模拟题 class Solution { private int maxIndex(int[] nums) { int tmp = Integer.MIN_VALUE,idx =0; 阅读全文
posted @ 2022-03-06 14:18 明卿册 阅读(21) 评论(0) 推荐(0) 编辑
摘要: 题目链接:https://leetcode-cn.com/problems/path-sum-ii/submissions/ 这道题需要对整个树进行遍历,对结果的存储可以用参数解决,所以不需要返回值。 class Solution { public List<List<Integer>> pathS 阅读全文
posted @ 2022-03-06 13:40 明卿册 阅读(17) 评论(0) 推荐(0) 编辑
摘要: 题目链接: 这是一道典型的,只需要对部分树进行搜索的题目,那么递归函数的返回值不能为void而为true。 还有一个技巧,为了处理方便不用进行求和,而是做减法即可。 递归1.0 class Solution { public boolean hasPathSum(TreeNode root, int 阅读全文
posted @ 2022-03-06 13:15 明卿册 阅读(14) 评论(0) 推荐(0) 编辑
上一页 1 2 3 4 5 6 ··· 15 下一页