代码随想录第十五天(一刷&&C语言)|平衡二叉树&&二叉树的所有路径&&左叶子之和

创作目的:为了方便自己后续复习重点,以及养成写博客的习惯。

一、反转字符串

思路:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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;
}

全篇后记:

多熟悉,似乎思路也变得清晰了一些,加油坚持就是胜利

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值