diff --git a/problems/0129.求根到叶子节点数字之和.md b/problems/0129.求根到叶子节点数字之和.md index 3439cd25..7f50c885 100644 --- a/problems/0129.求根到叶子节点数字之和.md +++ b/problems/0129.求根到叶子节点数字之和.md @@ -164,6 +164,52 @@ public: Java: +```java +class Solution { + List path = new ArrayList<>(); + int res = 0; + public int sumNumbers(TreeNode root) { + // 如果节点为0,那么就返回0 + if (root == null) return 0; + // 首先将根节点放到集合中 + path.add(root.val); + // 开始递归 + recur(root); + return res; + } + + public void recur(TreeNode root){ + if (root.left == null && root.right == null) { + // 当是叶子节点的时候,开始处理 + res += listToInt(path); + return; + } + + if (root.left != null){ + // 注意有回溯 + path.add(root.left.val); + recur(root.left); + path.remove(path.size() - 1); + } + if (root.right != null){ + // 注意有回溯 + path.add(root.right.val); + recur(root.right); + path.remove(path.size() - 1); + } + return; + } + public int listToInt(List path){ + int sum = 0; + for (Integer num:path){ + // sum * 10 表示进位 + sum = sum * 10 + num; + } + return sum; + } +} +``` + Python: ```python3 class Solution: diff --git a/problems/0143.重排链表.md b/problems/0143.重排链表.md index 76df63b7..2b4e68b7 100644 --- a/problems/0143.重排链表.md +++ b/problems/0143.重排链表.md @@ -177,6 +177,7 @@ public: Java: ```java +// 方法三 public class ReorderList { public void reorderList(ListNode head) { ListNode fast = head, slow = head; @@ -219,6 +220,76 @@ public class ReorderList { return headNode.next; } } + +------------------------------------------------------------------------- +// 方法一 Java实现,使用数组存储节点 + class Solution { + public void reorderList(ListNode head) { + // 双指针的做法 + ListNode cur = head; + // ArrayList底层是数组,可以使用下标随机访问 + List list = new ArrayList<>(); + while (cur != null){ + list.add(cur); + cur = cur.next; + } + cur = head; // 重新回到头部 + int l = 1, r = list.size() - 1; // 注意左边是从1开始 + int count = 0; + while (l <= r){ + if (count % 2 == 0){ + // 偶数 + cur.next = list.get(r); + r--; + }else { + // 奇数 + cur.next = list.get(l); + l++; + } + // 每一次指针都需要移动 + cur = cur.next; + count++; + } + // 当是偶数的话,需要做额外处理 + if (list.size() % 2== 0){ + cur.next = list.get(l); + cur = cur.next; + } + + // 注意结尾要结束一波 + cur.next = null; + } +} +------------------------------------------------------------------------- +// 方法二:使用双端队列,简化了数组的操作,代码相对于前者更简洁(避免一些边界条件) +class Solution { + public void reorderList(ListNode head) { + // 使用双端队列的方法来解决 + Deque de = new LinkedList<>(); + // 这里是取head的下一个节点,head不需要再入队了,避免造成重复 + ListNode cur = head.next; + while (cur != null){ + de.offer(cur); + cur = cur.next; + } + cur = head; // 回到头部 + + int count = 0; + while (!de.isEmpty()){ + if (count % 2 == 0){ + // 偶数,取出队列右边尾部的值 + cur.next = de.pollLast(); + }else { + // 奇数,取出队列左边头部的值 + cur.next = de.poll(); + } + cur = cur.next; + count++; + } + cur.next = null; + } +} + ``` Python: