day 17|leetcode|C++|110. 平衡二叉树|257. 二叉树的所有路径|404. 左叶子之和

Leetcode 110. 平衡二叉树

链接110. 平衡二叉树

thought

  • 一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

  • 无需多言,DFS递归思路:

  • 既然我们要判断所有的二叉树的左右子树的高度差,我们采用后序遍历,从左下逐个开始遍历,记录左右子树高度,并返回max(num1, num2)+1,并逐层封装返回上层,本题基本思路和求最大深度基本相同,多了判断高度差而已。

完整C++代码如下

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        bool test = true;
        maxDepth(root, test);
        return test;
    }
    int maxDepth(TreeNode* root, bool& test) {
        if (!root)
            return 0;
        int num1 = maxDepth(root->left,test);
        int num2 = maxDepth(root->right,test);
        if (!test)
            return 0;
        if (abs(num1 - num2) > 1)
            test = false;
        return max(num1, num2)+1;
    }
};

Leetcode 257. 二叉树的所有路径

链接257. 二叉树的所有路径

thought

  • 求所有路径,立刻想到了先序遍历的优点

完整C++代码如下

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if(!root)return res;
        recursion1(root, res);
        return res;
    }
    void recursion1(TreeNode* root, vector<string>& res) {
        static string cur;
        if (!root->left && !root->right) {
            if (!cur.empty()) {
                cur.erase(cur.size() - 2,2);
                res.push_back(cur);
            }
            return;
        }
        cur += to_string(root->val);
        cur += "->";
        if (root->left)
            recursion1(root->left, res);
        if (root->right)
            recursion1(root->right, res);
        return;
    }
};

class Solution {
public:
    void getPath(TreeNode* node, string path, vector<string>& ans) {
        path += to_string(node->val);
        if (node->left == NULL && node->right == NULL) {
            ans.push_back(path);
            return;
        }
        if (node->left)
            getPath(node->left, path + "->", ans);
        if (node->right)
            getPath(node->right, path + "->", ans);
        return;
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        string path;
        vector<string> ans;
        if (root == NULL)
            return ans;
        getPath(root, path, ans);
        return ans;
    }
};

Leetcode 404. 左叶子之和

链接404. 左叶子之和

thought:先序遍历

完整C++代码如下

class Solution {
public:
    int res = 0;
    int sumOfLeftLeaves(TreeNode* root) {
        dfs(root);
        return res;
    }
    void dfs(TreeNode* root) {
        if (root == nullptr) {
            return;
        }
        if (root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr) {
            res += root->left->val;
        }
        dfs(root->left);
        dfs(root->right);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值