二叉树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;
    }
相关推荐
地平线开发者18 分钟前
征程 6 | cgroup sample
算法·自动驾驶
姓蔡小朋友1 小时前
算法-滑动窗口
算法
君义_noip1 小时前
信息学奥赛一本通 2134:【25CSPS提高组】道路修复 | 洛谷 P14362 [CSP-S 2025] 道路修复
c++·算法·图论·信息学奥赛·csp-s
kaikaile19952 小时前
基于拥挤距离的多目标粒子群优化算法(MO-PSO-CD)详解
数据结构·算法
不忘不弃2 小时前
求两组数的平均值
数据结构·算法
leaves falling2 小时前
迭代实现 斐波那契数列
数据结构·算法
珂朵莉MM2 小时前
全球校园人工智能算法精英大赛-产业命题赛-算法巅峰赛 2025年度画像
java·人工智能·算法·机器人
Morwit2 小时前
*【力扣hot100】 647. 回文子串
c++·算法·leetcode
DonnyCoy2 小时前
Android性能之数据结构
数据结构
天赐学c语言2 小时前
1.7 - 删除排序链表中的重要元素II && 哈希冲突常用解决冲突方法
数据结构·c++·链表·哈希算法·leecode