Day15 二叉树 | LeetCode 110. 平衡二叉树, 257. 二叉树的所有路径, 404. 左叶子之和

LeetCode 110. 平衡二叉树

class Solution {
public:
    int height(TreeNode* root) {
        if (!root) {
            return 0;
        }
        int leftH = height(root->left);
        int rightH = height(root->right);
        if (leftH == - 1 || rightH == - 1 || abs(leftH - rightH) > 1) {
            return -1;
        }else {
            return max(leftH, rightH) + 1;
        }
    }
    bool isBalanced(TreeNode* root) {
        return height(root) == -1 ? false : true;
    }
};

LeetCode 257. 二叉树的所有路径

回溯1
class Solution {
public:
    void traversal(TreeNode* root, vector<int>& path, vector<string>& res) {
        path.push_back(root->val);
        if (!root->left && !root->right) {
            string spath;
            for (int i = 0; i < path.size() - 1; i++) {
                spath += to_string(path[i]) + "->";
            }
            spath += to_string(path[path.size() - 1]);
            res.push_back(spath);
            return;
        }
        if (root->left) {
            traversal(root->left, path, res);
            path.pop_back();
        }
        if (root->right) {
            traversal(root->right, path, res);
            path.pop_back();
        }
    }

    vector<string> binaryTreePaths(TreeNode* root) {
        vector<int> path;
        vector<string> res;
        if (!root) {
            return res;
        }
        traversal(root, path, res);
        return res;
    }
};
回溯2
class Solution {
public:
    void traversal(TreeNode* root, string path, vector<string>& res) {
        path += to_string(root->val);
        if (!root->left && !root->right) {
            res.push_back(path);
            return;
        }
        if (root->left) {
            traversal(root->left, path + "->", res);
        }
        if (root->right) {
            traversal(root->right, path + "->", res);
        }
    }

    vector<string> binaryTreePaths(TreeNode* root) {
        string path;
        vector<string> res;
        if (!root) {
            return res;
        }
        traversal(root, path, res);
        return res;
    }
};

LeetCode 404. 左叶子之和

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (!root || (!root->left && !root->right)) {
            return 0;
        }
        int leftSum = sumOfLeftLeaves(root->left);
        if (root->left && !root->left->left && !root->left->right) {
            leftSum = root->left->val;
        }
        int rightSum = sumOfLeftLeaves(root->right);
        return leftSum + rightSum;

    }
};

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值