二叉树(1)

前面一些简单题就没放上来,放的都是一开始没思路的

110平衡二叉树

显然这题不能单纯的返回true false 还需要把这一层的高度接住
所以用-1作为标识符,如果=-1说明下层已经有不平衡了,那么都返回-1
否则就返回这棵树的高度

class Solution {
public:
    int getDepth(TreeNode * root)
    {
        if(root==nullptr)
        {
            return 0;
        }
        int left=getDepth(root->left);
        int right=getDepth(root->right);
        if(left==-1||right==-1)
        {
            return -1;
        }
        if(abs(left-right)>1)
        {
            return -1;
        }
        return max(left,right)+1;
    }
    bool isBalanced(TreeNode* root) {
        return !(getDepth(root)==-1);
    }
};

257二叉树的所有路径

能过,但是感觉不优雅

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

    }
};

这下舒服多了

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

    }
};

posted @ 2024-01-29 19:20  LiviaYu  阅读(3)  评论(0)    收藏  举报