哈希表记录每个元素 或者 使用三指针
class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
int n = nums.size();
int ans = 0;
for (int i = 0, j = 1, k = 2; i < n - 2 && j < n - 1 && k < n; i++) {
while (j < n - 1 && nums[j] < nums[i] + diff) {
j++;
}
while (k < n && nums[k] < nums[j] + diff) {
k++;
}
if (k >= n) break;
if (nums[i] + diff == nums[j] && nums[j] + diff == nums[k]) {
ans++;
j++;
k++;
}
}
return ans;
}
};
当不平衡时,直接返回-1,减少递归次数
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def dfs(node):
if not node:
return 0
l_height = dfs(node.left)
if l_height == -1:
return -1
r_height = dfs(node.right)
if r_height == -1:
return -1
if abs(l_height - r_height) > 1:
return -1
return max(l_height, r_height) + 1
return dfs(root) != -1
迭代法
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
stack<TreeNode*> node_stack;
stack<string> path_stack;
if (root == nullptr) return ans;
node_stack.push(root);
path_stack.push(to_string(root->val));
while (!node_stack.empty()) {
string path = path_stack.top();
path_stack.pop();
TreeNode* cur = node_stack.top();
node_stack.pop();
if (cur->left == nullptr && cur->right == nullptr) {
ans.emplace_back(path);
}
if (cur->right) {
node_stack.push(cur->right);
path_stack.push(path + "->" + to_string(cur->right->val));
}
if (cur->left) {
node_stack.push(cur->left);
path_stack.push(path + "->" + to_string(cur->left->val));
}
}
return ans;
}
};
递归
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
ans = []
def dfs(node, path):
if not node.left and not node.right:
ans.append(path)
return
if node.left:
dfs(node.left, path + "->" + str(node.left.val))
if node.right:
dfs(node.right, path + "->" + str(node.right.val))
return
dfs(root, str(root.val))
return ans
递归
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
ans = 0
def dfs(node, is_left):
if not node:
return
if is_left and not node.left and not node.right:
nonlocal ans
ans += node.val
return
dfs(node.left, True)
dfs(node.right, False)
return
dfs(root, False)
return ans