Leetcode- Symmetric Tree

Hyung Jun·2020년 12월 13일
0

Algorithm

목록 보기
2/14
post-thumbnail

Symmetric Tree

Description

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

Example

Code

#include <bits/stdc++.h>

using namespace std;

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 recursion(TreeNode *left, TreeNode *right)
    {
        if (!left && !right)
            return true;
        if (!left && right || left && !right)
            return false;

        if (left->val == right->val)
        {
            if (recursion(left->left, right->right) && recursion(left->right, right->left))
                return true;
        }

        return false;
    }

    bool isSymmetric(TreeNode *root)
    {
        if (!root)
            return true;

        if ((!root->left && root->right) || (root->left && !root->right))
            return false;
        if (!root->left && !root->right)
            return true;

        if (root->left->val == root->right->val)
        {
            if (BFS(root->left, root->right))
                return true;
        }
        return false;
    }
};

Thoughts

I thought this problem can be solved in many ways. Literally, I could use DFS, BFS, and just Recursive way. I think it is very easy to solve it through recursive way by comparing left node of given left node and right node of given right node. If those result is true, then I compare right of left and left of right , so on.
By doing that way, I think the order of the parameters in the recursive method, it is as same order as BFS.

profile
Keep Learning👨🏻‍💻

0개의 댓글