101. Symmetric Tree

原创 2016年08月30日 09:23:38

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

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

/**
 * 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 {
public:
    bool isSymmetric(TreeNode* root) {
         if (!root)
            return true;
         else
            return testSymmetric(root->left,root->right);
    }
    bool testSymmetric(TreeNode* left,TreeNode* right)
    {
      if (!left&&!right)
         return true;
      else if (!left&&right)  return false;
      else if (left&&!right)  return false;
      else if (left&&right&&left->val!=right->val) return false;
      else return testSymmetric(left->left,right->right)&&testSymmetric(left->right,right->left);
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

101. Symmetric Tree

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

101:Symmetric Tree【树】【DFS】

题目链接:click~ :解法1:队列 /*题意:判断一颗二叉树是否是自己的镜像*/ /** *思路: 只要保证根结点下的左子树的每一层是右子树的镜像,此树是自己的镜像 * ...

LeetCode 101. Symmetric Tree

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

leetcode || 101、Symmetric Tree

problem: Given a binary tree, check whether it is a mirror of itself (ie, symmetric aro...

LeetCode#101. Symmetric Tree

101. Symmetric Tree Given a binary tree, check whether it is a mirror of itself (ie, symmetric aroun...

【Leetcode】101. Symmetric Tree

方法一:递归: 思路: (1)若树为空,直接返回true。否则调用判断左右子树是否对称的函数isSymmetricTree(root.left, root.right)。 (2)判断左右子树是否对称:...

101. Symmetric Tree Leetcode Python

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

[LeetCode]101.Symmetric Tree

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

LeetCode 101. Symmetric Tree

101. Symmetric Tree一、问题描述 Given a binary tree, check whether it is a mirror of itself (ie, symmetr...

[leetcode] 101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). Fo...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)