17代码随想录训练营day17|part04

1、平衡二叉树

110. 平衡二叉树 - 力扣(LeetCode)

class Solution {
public:
    int getHeight(TreeNode* root) {
        if (!root) return 0;
        int leftheight = getHeight(root->left);
        if (leftheight == -1) return -1;
        int rightheight = getHeight(root->right);
        if (rightheight == -1) return -1;
        if (abs(leftheight - rightheight) > 1) return -1;
        return 1 + max(leftheight, rightheight);
    }
    bool isBalanced(TreeNode* root) {
        if (getHeight(root) == -1) return false;
        return true;
    }
};

2、二叉树的所有路径

257. 二叉树的所有路径 - 力扣(LeetCode)

class Solution {
public:
    void traversal(TreeNode* root, vector<int>& path, vector<string>& result) {
        // 前序遍历
        path.push_back(root->val);
        // 终止条件
        if (!root->left && !root->right) {
            string str = "";
            for (int i = 0; i < path.size() - 1; i++) {
                str += to_string(path[i]);
                str += "->";
            }
            str += to_string(path.back());
            result.push_back(str);
        }
        // 左
        if (root->left) {
            traversal(root->left, path, result);
            // 回溯
            path.pop_back();
        }
        // 右
        if (root->right) {
            traversal(root->right, path, result);
            // 回溯
            path.pop_back();
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<int> path;
        vector<string> result;
        traversal(root, path, result);
        return result;
    }
};

3、左叶子之和

404. 左叶子之和 - 力扣(LeetCode)

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (!root) return 0;
        if (!root->left && !root->right) return 0;
        int left = sumOfLeftLeaves(root->left);
        if (root->left && !root->left->left && !root->left->right) {
            left = root->left->val;
        }
        int right = sumOfLeftLeaves(root->right);
        return right + left;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值