[每日LeetCode] 101. Symmetric Tree

  |   0 评论   |   645 浏览

原文链接 [每日LeetCode] 101. Symmetric Tree

Description:

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

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

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

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

思路:本题要求判断二叉树是否为对称树。对称树的特点是镜面对称,开始考虑使用层次遍历,把每层的节点保存为数组,判断数组是否对称,后来发现不妥,第二个例子的情况就无法通过。后面使用[每日LeetCode] 100. Same Tree 思想,把一颗树拆成两棵树处理,依次判断每棵树的节点是否满足镜面对称。


C++代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    bool dfs(TreeNode* node1, TreeNode* node2)
    {
        if(node1 && node2)
        {
            if(node1->val != node2->val)
                return false;
            else
                return (dfs(node1->left, node2->right) && dfs(node1->right, node2->left));
        }
        else if(!node1 && !node2)
            return true;
        else
            return false;
    }
public:
    bool isSymmetric(TreeNode* root) {
        if(!root)
            return true;
        else
            return dfs(root->left,root->right);
    }
};

运行时间:8ms

运行内存:14.8M

评论

发表评论