创作目的:为了方便自己后续复习重点,以及养成写博客的习惯。
一、反转字符串
思路:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
ledcode题目:https://leetcode.cn/problems/balanced-binary-tree/description/
AC代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int height(struct TreeNode* root) {
if(root == NULL) {
return 0;
}else {
return fmax(height(root->left),height(root->right)) + 1;
}
}
bool isBalanced(struct TreeNode* root) {
if(root == NULL) {
return true;
}else {
return fabs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
}
二、二叉树的所有路径
思路:利用到回溯。
lecode题目:https://leetcode.cn/problems/binary-tree-paths/description/
AC代码:
void construct_paths(struct TreeNode* root, char** paths, int* returnSize, int* sta, int top) {
if (root != NULL) {
if (root->left == NULL && root->right == NULL) { // 当前节点是叶子节点
char* tmp = (char*)malloc(1001);
int len = 0;
for (int i = 0; i < top; i++) {
len += sprintf(tmp + len, "%d->", sta[i]);
}
sprintf(tmp + len, "%d", root->val);
paths[(*returnSize)++] = tmp; // 把路径加入到答案中
} else {
sta[top++] = root->val; // 当前节点不是叶子节点,继续递归遍历
construct_paths(root->left, paths, returnSize, sta, top);
construct_paths(root->right, paths, returnSize, sta, top);
}
}
}
char** binaryTreePaths(struct TreeNode* root, int* returnSize) {
char** paths = (char**)malloc(sizeof(char*) * 1001);
*returnSize = 0;
int sta[1001];
construct_paths(root, paths, returnSize, sta, 0);
return paths;
}
三、左叶子之和
思路:
ledcode题目:https://leetcode.cn/problems/sum-of-left-leaves/description/
AC代码:
bool isLeafNode(struct TreeNode *node) {
return !node->left && !node->right;
}
int dfs(struct TreeNode *node) {
int ans = 0;
if (node->left) {
ans += isLeafNode(node->left) ? node->left->val : dfs(node->left);
}
if (node->right && !isLeafNode(node->right)) {
ans += dfs(node->right);
}
return ans;
}
int sumOfLeftLeaves(struct TreeNode *root) {
return root ? dfs(root) : 0;
}
全篇后记:
多熟悉,似乎思路也变得清晰了一些,加油坚持就是胜利