day12打卡

ikun1111發表於2024-08-30

平衡二叉樹

class Solution
{
public:
int getheight(TreeNode *root)
{
if(root == nullptr)
{
return 0;
}
int left = getheight(root->left);
int right = getheight(root->right);
return 1+max(left, right);
}
bool isBalanced(TreeNode *root)
{
if(root == nullptr)
{
return true;
}
bool l = isBalanced(root->left);
bool r = isBalanced(root->right);
int left = getheight(root->left);
int right = getheight(root->right);
if(abs(left-right) <= 1 && l && r)
{
return true;
}
else
{
return false;
}

}

};

二叉樹所有的路徑

沒有想明白終止條件到空結點為啥不行
/**

  • Definition for a binary tree node.
  • struct TreeNode {
  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode() : val(0), left(nullptr), right(nullptr) {}
    
  • TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    
  • TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    
  • };
    */
    class Solution
    {
    public:
    void traversal(TreeNode root, vector &path, vector &ret)
    {
    path.push_back(root->val);
    if(root->left == nullptr && root->right == nullptr)
    {
    string str;
    for(int i = 0; i < path.size() - 1; ++i)
    {
    str += to_string(path[i]);
    str += "->";
    }
    str += to_string(path[path.size()-1]);
    ret.push_back(str);
    }
    if(root->left)
    {
    traversal(root->left, path, ret);
    path.pop_back();
    }
    if(root->right)
    {
    traversal(root->right, path, ret);
    path.pop_back();
    }
    }
    vector binaryTreePaths(TreeNode
    root)
    {
    vector path;
    vector ret;
    if(root == nullptr)
    {
    return ret;
    }
    traversal(root, path, ret);
    return ret;
    }
    };

左葉子之和

class Solution
{
public:
int traversal(TreeNode *root)
{
int left = 0;
int right = 0;
if(root == nullptr)
{
return 0;
}
if(root->left == nullptr && root->right == nullptr)
{
return 0;
}
left = traversal(root->left);
if(root->left)
{
if(root->left->left == nullptr && root->left->right == nullptr)
{
left = root->left->val;
}

    }
    if(root->right)
    {
        right = traversal(root->right);
    }
    return left + right;
}
int sumOfLeftLeaves(TreeNode* root)
{
    if(root == nullptr)
    {
        return 0;
    }
    return traversal(root);
}

};

完全二叉樹的結點個數
class Solution
{
public:
int countNodes(TreeNode *root)
{
if(root == nullptr)
{
return 0;
}
int left = countNodes(root->left);
int right = countNodes(root->right);
return 1+left+right;
}
};