代码随想录算法训练营第十七天|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;
    }
};
相关推荐
Kx_Triumphs2 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎2 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
Darkwanderor2 小时前
对Linux的进程控制的研究
linux·运维·c++
云泽8083 小时前
从零吃透 C++ 异常:抛出捕获、栈展开、异常重抛与编码规范详解
开发语言·c++·代码规范
轻颂呀3 小时前
约瑟夫环问题
算法
REDcker3 小时前
libdatachannel 快速入门
c++·webrtc·datachannel
凤凰院凶涛QAQ4 小时前
《Java版数据结构 & 集合类剖析》栈与队列:“push/pop 是栈的灵魂,offer/poll 是队列的骨架——四组 API,两种人生”
java·开发语言·数据结构
科技大视界5 小时前
投资AI项目,传统尽调不够用了——李章虎律师拆解算法、数据、算力三大雷区
人工智能·算法·数据挖掘
second605 小时前
第一部分:快速上手 —— 建立 C++ 基本语法与编程范式
开发语言·c++