代码随想录算法训练营day17 | ● 110.平衡二叉树 ● 257. 二叉树的所有路径 ● 404.左叶子之和

110.平衡二叉树

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 result;
        if(abs(leftHeight - rightHeight) > 1){
            result = -1;
        }
        else{
            result = 1 + max(leftHeight, rightHeight);
        }
        return result;
    }

    bool isBalanced(TreeNode* root) {
        return getHeight(root) == -1?   false : true; 
    }
};

257.二叉树的所有路径

class Solution {
public:

    void traversal(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){
            traversal(cur->left, path, result);
            path.pop_back(); //回溯
        }
        if(cur->right){
            traversal(cur->right, path, result);
            path.pop_back(); //回溯
        }
    }

    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> result;
        vector<int> path;
        if(root == NULL)    return result;
        traversal(root, path, result);
        return result;
    }
};

to_string():将当前值转换为字符串

404.左叶子之和

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(root == NULL)  return 0;
        if(root->left == NULL && root->right == NULL) return 0;

        int leftValue = sumOfLeftLeaves(root->left);    //左
        if(root->left != NULL && root->left->left == NULL 
            && root->left->right == NULL){
                leftValue = root->left->val;
            }
        
        int rightValue = sumOfLeftLeaves(root->right); //右

        int sum = leftValue + rightValue;   //中
        return sum;
    }
};
posted @ 2023-09-23 10:55  zz子木zz  阅读(3)  评论(0编辑  收藏  举报