Ruizhi Ma's Blog

Keep Calm and Carry On

Problem 104

Maximum Depth of Binary Tree

问题描述 https://leetcode.com/problems/maximum-depth-of-binary-tree/ 解决思路 用递归解决DFS(深度优先)问题。递归的最重要的核心点就是两个:1. 递归出口是什么 2. 递归公式是什么。 在这里,递归的出口显然是root没有左右孩子;公式则是比较左右孩子最多的节点作为返回值,而找到左右孩子最多的节点有需要调用maxDept...

Problem 111

Minimum Depth of Binary Tree

问题描述 https://leetcode.com/problems/minimum-depth-of-binary-tree/ 解决思路 临界条件:root == null 递归公式:返回左右子树最小的那个,长度加1(因为还有root自己) 特殊状态:左右子树有一个为空树,则应该返回另一边的子树,因为深度并不在此处停止计算 代码 /** * Definition fo...

Problem 96

Unique Binary Search Trees

问题描述 https://leetcode.com/problems/unique-binary-search-trees/ 代码 class Solution { public int numTrees(int n) { if(n < 1) return 0; int[] nums = new int[n + 1]; nums...

Problem 100

Same Tree

问题描述 https://leetcode.com/problems/same-tree/ 解决思路 递归遍历树就可以,比较简单。 代码 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode rig...

Problem 94

Binary Tree Inorder Traversal

问题描述 https://leetcode.com/problems/binary-tree-inorder-traversal/ 代码 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode righ...

Problem 91

Decode Ways

问题描述 https://leetcode.com/problems/decode-ways/ 代码 class Solution { public int numDecodings(String s) { //corner case if(s == null || s.length() == 0) return 0; int siz...

Problem 92

Reverse Linked List II

问题描述 https://leetcode.com/problems/reverse-linked-list-ii/ 代码 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { va...

Problem 90

Subsets II

问题描述 https://leetcode.com/problems/subsets-ii/ 解决思路 同78题,需要加入判断重复。 代码 class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>&...

Problem 206

Reverse Linked List

问题描述 https://leetcode.com/problems/reverse-linked-list/ 代码 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val =...

Problem 89

Gray Code

问题描述 https://leetcode.com/problems/gray-code/ 解决思路 https://leetcode-cn.com/problems/gray-code/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by–12/ 代码 class Solution { public List<In...