Skip to content

101.Symmetric Tree #31

@niuworld

Description

@niuworld

Question:

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.

Answer:

class Solution {
public:
    bool isSymmetricPro(TreeNode *node1, TreeNode *node2){
        if( node1 == NULL && node2 == NULL)
        return true;
        if( node1 == NULL || node2 == NULL || node1 -> val != node2 -> val)
        return false;
        return isSymmetricPro(node1 -> left, node2 -> right)&&isSymmetricPro(node1 -> right, node2 -> left);
    }
    bool isSymmetric(TreeNode* root) {
        return (root == false )? true : isSymmetricPro( root -> left, root -> right);
    }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions