day11打卡

ikun1111發表於2024-08-30

翻轉二叉樹

class Solution
{
public:
void traversal(TreeNode root)
{
if(root == nullptr)
{
return;
}
traversal(root->left);
traversal(root->right);
TreeNode tmp = root->left;
root->left = root->right;
root->right = tmp;
}
TreeNode
invertTree(TreeNode
root)
{
traversal(root);
return root;
}
};

對稱二叉樹

class Solution
{
public:
bool compare(TreeNode *left, TreeNode right)
{
if(left == nullptr && right != nullptr)
{
return false;
}
else if(left != nullptr && right == nullptr)
{
return false;
}
else if(left == nullptr && right == nullptr)
{
return true;
}
else if(left->val != right->val)
{
return false;
}
bool outside = compare(left->left, right->right);
bool inside = compare(left->right, right->left);
return outside && inside;
}
bool isSymmetric(TreeNode
root)
{
return compare(root->left, root->right);
}
};

最大深度

class Solution
{
public:
int maxDepth(TreeNode* root)
{
if(root == nullptr)
{
return 0;
}
int left = maxDepth(root->left);
int right = maxDepth(root->right);
if(left > right)
{
return 1 + left;
}
else
{
return 1 + right;
}
}
};

最小深度

class Solution
{
public:
int minDepth(TreeNode* root)
{
if(root == nullptr)
{
return 0;
}
int left = minDepth(root->left);
int right = minDepth(root->right);
if(root->left == nullptr && root->right !=nullptr)
{
return 1 + right;
}
else if(root->right == nullptr && root->left != nullptr)
{
return 1 + left;
}
if(left > right)
{
return 1 + right;
}
else
{
return 1 + left;
}
}
};