题目描述1
笔者解答1.1
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<>();
circle(root,list);
return list;
}
public static void circle(TreeNode root,List<Integer> list){
if(root!=null){
circle(root.left,list);
list.add(root.val);
circle(root.right,list);
}
}
}
笔者分析1.2
我承认我偷懒了,题目问的是迭代法完成,我虽然看到了,但还是想都没想就用递归了。因为看到评论区用栈来实现迭代法求解二叉树的中序遍历,用的挺巧妙的,这里把这种方法贴出来。代码挺简洁的,就不做说明了。
class Solution{
public List<Integer> inorderTraversal(TreeNode root){
List<Integer> list=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while(cur!=null||!stack.isEmpty()){
if(cur!=null){
stack.push(cur);
cur=cur.left;
}else{
cur=stack.pop();
list.add(cur.val);
cur=cur.right;
}
}
return list;
}
}
题目描述2
笔者分析2.1
因为这题比较简单,所以应该看重的是效率问题。反正我写的代码不咋地,评论区也是神仙打架。直接来 个尾递归,代码简洁,效率高
public ListNode reverseList(ListNode head){
return reverse(null,head);
}
public static ListNode reverse(ListNode pre,ListNode cur){
if(cur==null) return pre;
ListNode next=cur.next;//自始至终next都是指向员链表的下一个结点
cur.next=pre;//但是原链表的下一个结点指向的却是新生成的链表,有点东西
return reverse(cur,next);
}
题目描述3
笔者分析3.1
起初我还以为要用到最短路径里的一些算法了,把我给整懵了,看到评论区的大佬解答,原来如此啊。真巧妙,动态规划。
public int minPathSum(int[][] grid){
int width=grid[0].length,high=grid.length;
if(high==0||width==0)return 0;
//初始化
for(int i=1;i<height;i++)grid[i][0]+=grid[i-1][0];
for(int i=1;i<width;i++)grid[0][i]+=grid[0][i-1];//这两步初始化就非常巧妙
for(int i=1;i<high;i++)
for(int j=1;j<width;j++)
grid[i][j]+=Math.min(grid[i-1][j],grid[i][j-1]);
return grid[high-1][width-1];
}
}
总结
建模比赛结束了,回到正轨,每日打卡第十四天,以下图为证