Symmetric Tree —— Leetcode

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.

递归的方法比较简单,稍后会将代码列出;

迭代的话,Discussion中有一个人是用一个queue保存结点,如上例,<2 2>,再判断两个点是否相等,左的左和右的右,左的右和右的左是否相等,相等同时进queue,不等则return false。

下面给出递归代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if(!root)   return true;
        return sym(root->left, root->right);
    }
    bool sym(TreeNode *tree1, TreeNode *tree2)
    {
        if(!tree1 && !tree2)    return true;
        if(!tree1&&tree2 || tree1&&!tree2)  return false;
        if(tree1->val != tree2->val)    return false;
        return sym(tree1->left, tree2->right) && sym(tree1->right, tree2->left);
    }
};

你可能感兴趣的:(Symmetric Tree —— Leetcode)