106.从中序与后序遍历序列构造二叉树
解题思路
- 找到根节点在中序序列的位置
- 计算左子树的节点个数
- 开辟一个节点,并把根节点的值赋值给这个节点
- 根节点的左孩子和右孩子重复上面几个步骤
代码实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
//返回以中序[l1, r1]和后序[l2, r2]的根节点
struct TreeNode* f(int* inorder, int l1, int r1, int* postorder, int l2, int r2, int map[]) {
if (r1 - l1 + 1 <= 0) {//如果树中的节点个数少于等于0,返回NULL
return NULL;
}
int n = map[postorder[r2] + 3000];//取出根节点在中序序列的位置
int k = n - l1;//计算左子树的节点个数
struct TreeNode* head = (struct TreeNode*)malloc(sizeof(struct TreeNode));//开辟一个节点
head -> val = postorder[r2];//给节点赋值
head -> left = f(inorder, l1, n - 1, postorder, l2, l2 + k - 1, map);//递归调用左子树
head -> right = f(inorder, n + 1, r1, postorder, l2 + k, r2 - 1, map);//递归调用左子树
return head;
}
struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) {
int map[6001] = {0};//用来记录在中序遍历的位置
for (int i = 0; i < inorderSize; i ++) {
map[inorder[i] + 3000] = i;//加3000是因为不能有负数,并且节点的值最小是-3000
}
return f(inorder, 0, inorderSize - 1, postorder, 0, postorderSize - 1, map);
}
P5534 【XR-3】等差数列
解题思路
- 先计算公差
- 利用等差数列求和公式算
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
#define u unsigned
#define ll long long
#define sc scanf
#define pr printf
#define fr(i, j, n) for (int i = j; i < n; i++)
#define N 10
ll a, b, n, d;
int main(int argc, char* argv[])
{
sc("%lld%lld%lld", &a, &b, &n);
d = b - a;
pr("%lld", n * a + (n - 1) * n / 2 * d);
return 0;
}
标签:map,21,int,题解,2024,include,inorder,节点,define
From: https://www.cnblogs.com/lwj1239/p/18025686