LeetCode:Symmetric Tree

原创 2015年11月18日 19:02:19

问题描述:

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 a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 * 
 * 递归版,时间复杂度O(n),空间复杂度O(logn)
 */
class Solution {
public:
  bool isSymmetric(TreeNode *root) {
    return root ? isSymmetric(root -> left,root -> right):true ;
 }
  bool isSymmetric(TreeNode *left,TreeNode * right) {
      if(!left && !right)  return true;
      if(!left || !right)  return false;
      return left -> val == right -> val && 
      isSymmetric(left -> left,right -> right) && 
      isSymmetric(left -> right,right -> left);
  }
};


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

相关文章推荐

【LeetCode】Symmetric Tree

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

leetcode || 101、Symmetric Tree

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

【LeetCode】Symmetric Tree

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

Symmetric Tree -- LeetCode

原题链接: http://oj.leetcode.com/problems/symmetric-tree/  这道题是树的题目,本质上还是树的遍历。这里无所谓哪种遍历方式,只需要对相应结点进行比较即可...

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(Symmetric Tree)判断二叉树是否是对称的

题目要求: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its cen...
  • lqcsp
  • lqcsp
  • 2014年04月15日 05:25
  • 546

[leetcode] 101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). Fo...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode:Symmetric Tree
举报原因:
原因补充:

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