目前比赛停滞在一半左右的名词,每次只是两道题
但这次虽然也打了两道题却感觉吃力,最近荒废刷题的原因,真的是一日不刷自己知道,三日不刷,比赛知道
可以不打比赛,但是不可以不写题解。只有思考才能进步
题解正文:
第二题:
知识点:二叉搜索树是有序树,左侧节点比跟节点小,右侧大,这道排序题有天然优势
问题:如何获得二叉树的值,遍历总是有问题,因为比赛的时候我的遍历代码是试出来的,不知道为啥能成功
原因:
值传递 VS 引用传递:
区分不清导致
值传递只要变现是在内存中新开辟一块变量,给赋值操作的对象,更改新对象不会影响旧对象
引用传递对新值的更改会连同旧的一起,所以整个递归操作一直是对同一个list进行添加,因此最后直接输出即可不用再次赋值
改进点:或许可以同步遍历两颗树,遍历完排序完,而不是先存储后排序
改进点:
5296. All Elements in Two Binary Search Trees
Given two binary search trees root1
and root2
.
Return a list containing all the integers from both trees sorted in ascending order.
Example 1:
Input: root1 = [2,1,4], root2 = [1,0,3] Output: [0,1,1,2,3,4]
Example 2:
Input: root1 = [0,-10,10], root2 = [5,1,7,0,2] Output: [-10,0,0,1,2,5,7,10]
Example 3:
Input: root1 = [], root2 = [5,1,7,0,2] Output: [0,1,2,5,7]
Example 4:
Input: root1 = [0,-10,10], root2 = [] Output: [-10,0,10]
Example 5:
Input: root1 = [1,null,8], root2 = [8,1] Output: [1,1,8,8]
Constraints:
- Each tree has at most
5000
nodes. - Each node's value is between
[-10^5, 10^5]
.
赛事代码:
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def getAllElements(self, root1, root2): """ :type root1: TreeNode :type root2: TreeNode :rtype: List[int] """ list1 = [] list2 = [] if root2==None: return self.getVal(root1, list1) if root1==None: return self.getVal(root2, list2) list1 = self.getVal(root1, list1) list2 = self.getVal(root2, list2) print(list1) print(list2) len_1 = len(list1) len_2 = len(list2) i, j = 0, 0 ans = [] while i != len_1 and j != len_2: if list1[i] <= list2[j]: ans.append(list1[i]) i += 1 else: ans.append(list2[j]) j += 1 if i != len_1: ans += list1[i:] else: ans += list2[j:] return ans print(list2) def getVal(self, root, res): if root.left: root3 = root.left res = self.getVal(root3, res) res.append(root.val) if root.right: root4 = root.right res = self.getVal(root4, res) return res
第三题:
5297. Jump Game III
Given an array of non-negative integers arr
, you are initially positioned at start
index of the array. When you are at index i
, you can jump to i + arr[i]
or i - arr[i]
, check if you can reach to any index with value 0.
Notice that you can not jump outside of the array at any time.
Example 1:
Input: arr = [4,2,3,0,3,1,2], start = 5 Output: true Explanation: All possible ways to reach at index 3 with value 0 are: index 5 -> index 4 -> index 1 -> index 3 index 5 -> index 6 -> index 4 -> index 1 -> index 3
Example 2:
Input: arr = [4,2,3,0,3,1,2], start = 0 Output: true Explanation: One possible way to reach at index 3 with value 0 is: index 0 -> index 4 -> index 1 -> index 3
Example 3:
Input: arr = [3,0,2,1,2], start = 2 Output: false Explanation: There is no way to reach at index 1 with value 0.
Constraints:
1 <= arr.length <= 5 * 10^4
0 <= arr[i] < arr.length
0 <= start < arr.length