二叉树part03(二)

  1. 平衡二叉树
cpp 复制代码
    int postorder(TreeNode* root) {
        if (root == NULL) return 0;

        int l = postorder(root->left);
        if (l == -1) return -1; // 只要出现-1 左子树中某个子树不是平衡二叉树,直接返回-1

        int r = postorder(root->right);
        if (r == -1) return -1;// 道理同上
        
        if (abs(l - r) > 1) return -1; // 尽管左右子树都是完全二叉树,两颗子树高度差>1 说明整颗树不是平衡二叉树

        int height = 1 + max(l,r);
        return height; // 否则返回最大高度
    }

    bool isBalanced(TreeNode* root) {
        if (postorder(root) == -1) return false;
        return true;
    }

257.二叉树的所有路径

cpp 复制代码
    vector<string> res;
    // 从根节点寻找所有路径,肯定是前序遍历,注意要保持字符串的输出格式
    void dfs(TreeNode* root, string s) {
        s += to_string(root->val);// 
        if (root->left == NULL && root->right == NULL) {
            res.push_back(s);
            return;
        }
        if (root -> left) dfs(root->left, s + "->"); 
        if (root -> right) dfs(root->right, s + "->");
        return;
    }

    vector<string> binaryTreePaths(TreeNode* root) { 
        res.clear();
        if (root == NULL) return res;
        string s;
        dfs(root, s);
        return res;
    }
  1. 二叉树的左叶子之和

看到本题可能一下想到层序遍历,其实没有那么简单,因为找的是左叶子不是左侧节点, 使用递归的话后序最好

cpp 复制代码
    // 后序方便一些
    int res = 0;
    void dfs(TreeNode* root) {
        // 看有无左儿子
        if (root->left) {
            // 判断左儿子是不是叶子
            if (root->left->left == NULL && root->left->right == NULL) {
                res += root->left->val;
                // 不是叶子就向下找
            }else dfs(root->left);
        } 
        // 右儿子直接向下找
        if (root->right) {
            dfs (root->right);
        }
        return;
    }

    int sumOfLeftLeaves(TreeNode* root) {
        // 节点数大于等于1
        if (root -> left == NULL && root->right == NULL) return res; // 节点数等于1和为0

        dfs(root);
        return res;
    }
相关推荐
V搜xhliang02462 分钟前
OpenClaw科研全场景用法:从文献到实验室的完整自动化方案
运维·开发语言·人工智能·python·算法·microsoft·自动化
汉克老师17 分钟前
GESP2025年3月认证C++五级( 第三部分编程题(2、原根判断))
c++·算法·模运算·gesp5级·gesp五级·原根·分解质因数
数据皮皮侠39 分钟前
上市公司创新韧性数据(2000-2024)|顶刊同款 EIR 指数
大数据·人工智能·算法·智慧城市·制造
WL_Aurora42 分钟前
Python 算法基础篇之链表
python·算法·链表
科研前沿1 小时前
纯视觉无感解算 + 动态数字孪生:室内外无感定位技术全新升级
大数据·人工智能·算法·重构·空间计算
代码中介商1 小时前
数据结构开篇:从问题到解决方案
数据结构
Wadli1 小时前
26.单调栈
算法
晨曦夜月1 小时前
进程的五大状态及特殊进程解析
linux·服务器·算法
吟安安安安2 小时前
适合短期冲刺的学习工作流(针对算法)
学习·算法
科研前沿2 小时前
什么是时空融合技术?
大数据·人工智能·数码相机·算法·重构·空间计算