LeetCode 654.最大二叉树 分析1.0 if(start == end) return节点索引 locateMaxNode(arr,start,end) new root = 最大索引对应节点 max.right = 最大节点右侧子数组的最大值 要保证能够递归 max.left = 最大节点左侧子数组的最大值 class Solution { int cnt = 1; public TreeNode constructMaximumBinaryTree(int[] nums) { re…
LeetCode 513.找树左下角的值 分析1.0 二叉树的 最底层 最左边 节点的值,层序遍历获取最后一层首个节点值,记录每一层的首个节点,当没有下一层时,返回这个节点 class Solution { ArrayDeque<TreeNode> queue = new ArrayDeque(); int res = 0; public int findBottomLeftValue(TreeNode root) { queue.offer(root); return levelOrder(…
LeetCode 235. 二叉搜索树的最近公共祖先 分析1.0  二叉搜索树根节点元素值大小介于子树之间,所以只要找到第一个介于他俩之间的节点就行 class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root.val >= p.val && root.val <= q.val){ return root; }else if(root.…
LeetCode 530.二叉搜索树的最小绝对差 分析1.0 二叉搜索树,中序遍历形成一个升序数组,节点差最小值一定在中序遍历两个相邻节点产生 ✡✡✡ 即 双指针思想在树遍历中的应用 class Solution { TreeNode pre;// 记录上一个遍历的结点 int result = Integer.MAX_VALUE; public int getMinimumDifference(TreeNode root) { if(root==null)return 0; traversal…
前言   考研结束半个月了,自己也简单休整了一波,估了一下分,应该能进复试,但还是感觉不够托底.不管怎样,要把代码能力和八股捡起来了,正好看到卡哥有这个算法训练营,遂果断参加,为机试和日后求职打下一个基础.   我之前断断续续地刷过一些LeetCode,但是不成体系,数量也少得可怜,才区区50+,在寻找暑期实习的过程中吃够了苦头,希望通过这次训练营得到一个长足的提升,养成自己写博客的习惯,慢慢提升自己的博客水准. 之前的LeetCode刷题分析 LeetCode 704 二分查找   二分是一个…
基础知识 二叉树基础知识 二叉树多考察完全二叉树.满二叉树,可以分为链式存储和数组存储,父子兄弟访问方式也有所不同,遍历也分为了前中后序遍历和层次遍历 Java定义 public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) {…
LeetCode 110.平衡二叉树 分析1.0 求左子树高度和右子树高度,若高度差>1,则返回false,所以我递归了两遍 class Solution { public boolean isBalanced(TreeNode root) { if(root == null){ return true; } int left = postOrder(root.left); int right = postOrder(root.right); if(Math.abs(left-right)>1…
基础知识 二叉树的多种遍历方式,每种遍历方式各有其特点 LeetCode 104.二叉树的最大深度 分析1.0 往下遍历深度++,往上回溯深度-- class Solution { int deep = 0, max = 0; public int maxDepth(TreeNode root) { preOrder(root); return max; } void preOrder(TreeNode p){ if(p == null){ return; } deep++; max = Mat…
层序遍历 /** * 二叉树的层序遍历 */ class QueueTraverse { /** * 存放一层一层的数据 */ public List<List<Integer>> resList = new ArrayList<>(); public List<List<Integer>> levelOrder(TreeNode root) { traverse(root, resList); return resList; } /** * 树…
leetcode 977   分析1.0:   要求对平方后的int排序,而给定数组中元素可正可负,一开始有思维误区,觉得最小值一定在0左右徘徊,但数据可能并不包含0:遂继续思考,发现元素分布有三种情况,递增.递减以及类似二元凹函数,而题目要求O(n)的时间复杂度,不可能采用十大排序算法,于是接下来打算寻找最小值及其索引位置向两侧寻找次小值并存放进新数组,遍历元素时逐个使用Math.abs()函数确定大小,一开始采用指针移动的思想比较,index,index+1,index+2得到最小值及索引,…