代码随想录算法训练营第十七天|LeetCode110 平衡二叉树、LeetCode257 二叉树的所有路径

题1:

指路:LeetCode110 平衡二叉树
思路与代码:

左右子树的高度差小于等于1。对于这个题,递归比迭代方便太多,我也想过迭代,但是我没有写出来,大家可以自己试一下。递归代码如下:

cpp 复制代码
class Solution {
public:
    //递归
    int getHeight  (TreeNode* node) {
        if (node == NULL) {return 0;}
        int leftHeight = getHeight(node->left);
        if (leftHeight == -1) return -1;
        int rightHeight = getHeight(node->right);
        if (rightHeight == -1) return -1;
        int ans = abs(leftHeight - rightHeight);
        if (ans > 1) return -1;  // 绝对值超过1符合条件
        else return 1 + max(leftHeight, rightHeight);
       /* return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight, rightHeight);*/
    } 
    bool isBalanced(TreeNode* root) {
    if (getHeight(root)== -1) 
    return false;
    return true;
    /*return getHeight(root) == -1 ? false : true;*/
    }
};

题2:

指路:LeetCode257 二叉树的所有路径
思路与代码:

递归进行前序遍历,找到子节点记录路径之后回溯回退路径。我还没会呢,先看看代码吧。

cpp 复制代码
class Solution {
private:
    void treversal(TreeNode* cur, vector<int>& path, vector<string>& result) {
        path.push_back(cur->val);
        if (cur->left == NULL && cur->right == NULL) {
            string sPath;
            for (int i = 0; i < path.size() - 1; i++) {
                sPath += to_string(path[i]);
                sPath += "->";
            }
            sPath += to_string(path[path.size() - 1]);
            result.push_back(sPath);
            return ;
        }
        if (cur->left) {
            treversal(cur->left, path, result);
            path.pop_back();
        }
        if (cur->right) {
            treversal(cur->right, path, result);
            path.pop_back();
        }
    }
    public:
    vector<string> binaryTreePaths(TreeNode* root) {
    vector<string> result;
    vector<int> path;
    if (root == NULL) return result;
    treversal(root, path, result);
    return result;
    }
};
相关推荐
无名猿1 分钟前
C++ lambda 捕获列表详解:值捕获、引用捕获、初始化捕获与悬垂引用
c++·现代c++·语法基础·踩坑记录
tangguofeng36 分钟前
基于分治策略的循环赛日程表问题的思路讲解
算法
hnjzsyjyj1 小时前
洛谷 P1339:[USACO09OCT] Heat Wave G ← Bellman-Ford 算法
数据结构·bellman-ford 算法
起个名字费劲死了1 小时前
VisionMaster集成深度学习算法(基础狗)
人工智能·深度学习·算法
lengxuenong1 小时前
枚举例题分析
c++·算法·青少年编程
繁华的地方不一定留下你的脚印1 小时前
C++线程如何安全停止与唤醒:std::jthread、stop_token与condition_variable
开发语言·c++
Navigator_Z1 小时前
LeetCode //C - 1269. Number of Ways to Stay in the Same Place After Some Steps
c语言·算法·leetcode
2601_965742221 小时前
短视频脚本创作方法分享:本地生活类账号的起步思路
大数据·人工智能·算法·ai·新媒体运营·生活
55873生态系统手记2 小时前
读完 55873 资产钱包的技术栈,我重新理解了 "合规钱包" 应该长什么样
算法·架构
旋生万物2 小时前
素数螺旋映射 $z_n=n^{1+i}$ 的角分布统计检验与零模型对比
大数据·前端·人工智能·算法·云原生·螺旋生成论·螺旋相位