leetcode打卡#day20 110.平衡二叉树、 257.二叉树的所有路径、 404.左子树之和

110. 平衡二叉树

class Solution {
public:
    int getHeight(TreeNode* node) {
        if (node == nullptr) return 0;
        //采用后序遍历
        int leftHeight = getHeight(node->left);
        if (leftHeight == -1) return -1;
        int rightHeight = getHeight(node->right);
        if (rightHeight == -1) return -1;
        //计算左右子树的高度差
        if (abs(leftHeight - rightHeight) > 1) return -1;
        else return 1 + max(leftHeight, rightHeight);
    }
    bool isBalanced(TreeNode* root) {
        int result = getHeight(root);
        //当返回值为-1时,说明已经不满足平衡二叉树的特性了
        return result == -1 ? false : true;
    }
};

257. 二叉树的所有路径

class Solution {
public:
    //to_string 将数字转化成字符串
    //这里有回溯的思想
    //采用前序遍历
    void getPath(TreeNode* node, vector<int>& path, vector<string>& paths) {
        if (node == nullptr) return;
        path.push_back(node->val);//path收集结点
        //遍历到叶子结点就可以把路径放入到结果集中
        if (node->left == nullptr && node->right == nullptr) {
            //将数字组合成字符
            string str = "";
            int size = path.size();
            for (int i = 0; i < size-1; i++) {
                str += to_string(path[i]);
                str += "->";
            }
            str += to_string(path[size-1]);
            //加入到结果集合中
            paths.push_back(str);
        }
        if (node->left) {
            getPath(node->left, path, paths);
            //回溯
            path.pop_back();
        }
        if (node->right) {
            getPath(node->right, path, paths);
            //回溯
            path.pop_back();
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> paths;//存放所有路径
        vector<int> path;// 存放单条路径
        getPath(root, path, paths);
        return paths;
    }
};

404. 左叶子之和

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (root == nullptr) return 0;
        if (root->left == nullptr && root->right == nullptr) return 0;
        //左
        int leftVal = sumOfLeftLeaves(root->left);
        if (root->left && root->left->left == nullptr && root->left->right == nullptr) {
            leftVal = root->left->val;
        }
        //右
        int rightVal = sumOfLeftLeaves(root->right);
        //中
        int sum = leftVal + rightVal;
        return sum;
    }
};
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值