LeetCode - Symmetric Tree

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

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

void traversalLeft(TreeNode* root, vector<int> &leftTreeValue) {
    if (NULL == root) {
        return;
    }

    traversalLeft(root->left, leftTreeValue);
    leftTreeValue.push_back(root->val);
    traversalLeft(root->right, leftTreeValue);
}

void traversalRight(TreeNode* root, vector<int> &rightTreeValue) {
    if (NULL == root) {
        return;
    }

    traversalRight(root->right, rightTreeValue);
    rightTreeValue.push_back(root->val);
    traversalRight(root->left, rightTreeValue);
}

bool isSymmetric(TreeNode *root) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function

    if (NULL == root) {
        return true;
    }
    vector<int> leftTreeValue;
    vector<int> rightTreeValue;
    traversalLeft(root->left, leftTreeValue);
    traversalRight(root->right, rightTreeValue);

    return leftTreeValue == rightTreeValue;
}


你可能感兴趣的:(LeetCode - Symmetric Tree)