代码随想录day17

110.平衡二叉树 
开始纠结函数的返回值是bool类型,但是本题必须要通过求高度来确定是否为平衡二叉树,所以辅助函数的返回值类型是int类型,用-1来表示不是平衡二叉树。
class Solution {
public:
    int getheight(TreeNode* node){
        if(node==NULL) return 0;
        int leftheight=getheight(node->left);
        //然后需要先判断一下返回值是不是-1,如果是的话直接返回-1
        if(leftheight==-1) return -1;
        int rightheight=getheight(node->right);
        if(rightheight==-1) return -1;
        int res;
        if(abs(rightheight-leftheight)>1) res=-1;
        else{
            res=max(leftheight,rightheight)+1;
        }
        return res;
    }
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        return getheight(root)==-1?false:true;
    }
};

257. 二叉树的所有路径 

必须要用前序遍历和回溯。

class Solution {
public:
    void traversal(TreeNode* cur,vector& path,vector& res){
        path.push_back(cur->val);
        if(!cur->left&&!cur->right){
            string sPath;
            for(int i=0;ileft){
            traversal(cur->left,path,res);
            //还需要回溯弹出元素,重新记录新的路径
            path.pop_back();
        }
        if(cur->right){
            traversal(cur->right,path,res);
            path.pop_back();
        }
        return;
    }
    vector binaryTreePaths(TreeNode* root) {
        vector res;
        vector path;
        if(!root) return res;
        traversal(root,path,res);
        return res;
    }
};

404.左叶子之和(需要多重复)

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

你可能感兴趣的:(leetcode,算法,职场和发展)