春节7天练 | Day 5:二叉树和堆

本文深入探讨了二叉树的几种关键算法,包括翻转二叉树、计算最大深度、验证二叉搜索树及路径总和查找。通过具体实现代码,详细解释了每种算法的工作原理,为读者提供了一个全面理解二叉树操作的视角。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Invert Binary Tree(翻转二叉树)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* invertTree(struct TreeNode* root) {
    if(root == NULL)
        return NULL;
    struct TreeNode* left = root->left;
    root->left = invertTree(root->right);
    root->right = invertTree(left);
    return root;
}

Maximum Depth of Binary Tree

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int maxDepth(struct TreeNode* root) {
    if(root == NULL)
        return 0;
    if(root->left==NULL&&NULL==root->right)
        return 1;
    int left =  maxDepth(root->left);
    int right = maxDepth(root->right);
    return left>right ? (left+1):(right+1);
}

ps:不单独赋值left right 容易超时

Validate Binary Search Tree

bool helper(struct TreeNode* root, int* lower_bound, int* upper_bound) {
    if(root == NULL) return true;
    
    int lower_bound_left, upper_bound_left, lower_bound_right, upper_bound_right;
    bool bst_left = helper(root->left, &lower_bound_left, &upper_bound_left);
    bool bst_right = helper(root->right, &lower_bound_right, &upper_bound_right);
    
    if((root->right && root->val >= lower_bound_right) || (root->left && root->val <= upper_bound_left))
        return false;
    
    *upper_bound = root->right == NULL ? root->val : upper_bound_right;
    *lower_bound = root->left == NULL ? root->val : lower_bound_left;
    
    return bst_left && bst_right;
}

bool isValidBST(struct TreeNode* root) {
    int lower_bound, upper_bound;
    return helper(root, &lower_bound, &upper_bound);
}

ps:重点在于所有子节点和祖先节点的大小关系要一直保持

Path Sum

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool hasPathSum(struct TreeNode* root, int sum) {
    if(root == NULL)
        return false;
    if(root->left==NULL&&root->right==NULL)
        return sum==root->val;
    return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值