29. Symmetric Tree
02 Jul 2020 | Daily Algorithms
Recursive Solution
/**
* 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:
bool isSymmetric(TreeNode* root) {
if(!root)
return true;
return isSymmetric(root->left,root->right);
}
bool isSymmetric(TreeNode* l, TreeNode* r)
{
if(!l && !r)
return true;
else if(!l || !r)
{
return false;
}
if(l->val != r->val)
{
return false;
}
return isSymmetric(l->left,r->right) && isSymmetric(l->right,r->left); // 동시에 확인
}
};
Recursive Solution
/**
* 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:
bool isSymmetric(TreeNode* root) {
if(!root)
return true;
return isSymmetric(root->left,root->right);
}
bool isSymmetric(TreeNode* l, TreeNode* r)
{
if(!l && !r)
return true;
else if(!l || !r)
{
return false;
}
if(l->val != r->val)
{
return false;
}
return isSymmetric(l->left,r->right) && isSymmetric(l->right,r->left); // 동시에 확인
}
};
Comments