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

方法:

利用递归解决

C++代码:

/**
 * 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 helper(root->left, root->right);
    }
    
    bool helper(TreeNode* left, TreeNode* right)
    {
        if(!left && !right)
            return true;
        if((left && !right) || (!left && right))
            return false;
        return left->val == right->val && helper(left->right, right->left) && helper(left->left, right->right);
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,453评论 0 10
  • Symmetric Tree Given a binary tree, check whether it is a...
    sherrysack阅读 259评论 0 0
  • title: Symmetric Treetags:- symmetric-tree- No.101- simpl...
    yangminz阅读 179评论 0 0
  • 一年半前,发现背后有个肿块,不痛不痒,但是越来越大,有点担心,去医院做了各种检查,确诊为脂肪瘤。 原本...
    肥妹蜉蝣记阅读 539评论 0 0
  • 不经历世道人事,轻言看空淡然,总欠一些沧桑。 不在红尘里打个滚,不够论佛道。 不尝够爱情的苦痛磨难,不会淡然放下。...
    姜牧之5373阅读 404评论 0 0