leetcode101题 题解 翻译 C语言版 Python版
2016-04-14 21:34
501 查看
101. 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:
But the following is not:
Note:
Bonus points if you could solve it both recursively and iteratively.
101.对称树
给定一棵二叉树,检查它是否是它自身的镜像(即:轴对称)
举个例子,这棵二叉树是对称的:
但是下面这个就不是:
思路:这题用递归很好解决,开始时将左子树和右子树分别递归下去,如果第一棵树的左子树和第二棵树的右子树递归下去完全相同,同时第一棵树的右子树和第二棵树的左子树递归下去完全相同,那么这两棵树就满足对称了。如果根结点的两棵子树满足对称了,那么整棵树就是对称的了。
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.
101.对称树
给定一棵二叉树,检查它是否是它自身的镜像(即:轴对称)
举个例子,这棵二叉树是对称的:
1 / \ 2 2 / \ / \ 3 4 4 3
但是下面这个就不是:
1 / \ 2 2 \ \ 3 3
思路:这题用递归很好解决,开始时将左子树和右子树分别递归下去,如果第一棵树的左子树和第二棵树的右子树递归下去完全相同,同时第一棵树的右子树和第二棵树的左子树递归下去完全相同,那么这两棵树就满足对称了。如果根结点的两棵子树满足对称了,那么整棵树就是对称的了。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool isSymmetriclr(struct TreeNode* left, struct TreeNode* right){ if (left == NULL && right == NULL) return true; if (left == NULL && right != NULL) return false; if (left != NULL && right == NULL) return false; if (left->val != right->val) return false; if (!isSymmetriclr(left->left, right->right)) return false; if (!isSymmetriclr(left->right, right->left)) return false; return true; } bool isSymmetric(struct TreeNode* root) { if (root == NULL) return true; return isSymmetriclr(root->left, root->right); }
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True return self.isSymmetriclr(root.left, root.right) def isSymmetriclr(self, left, right): if not (left or right): return True if (left and right==None) or (left==None and right): return False if left.val != right.val: return False if not self.isSymmetriclr(left.left, right.right): return False if not self.isSymmetriclr(left.right, right.left): return False return True
相关文章推荐
- C语言中以十六进制输出字符型变量会出现'ffffff"的问题
- Teacher_Cadre c++多文件编程
- C语言中的sizeof和strlen
- [C语言][LeetCode][234]Palindrome Linked List
- c++的三次作业
- C语言变量与内存分配
- c++ map、multimap 的使用方法
- [C语言][LeetCode][2]Add Two Numbers
- 关于C++类型检查的一点小挫折
- 线程池原理及创建(C++实现)
- C语言学习笔记(结构体对齐问题)
- C/C++深度分析
- C/C++中各种类型int、long、double、char表示范围(最大最小值)
- 禁用编译器自动生成的函数(Effective C++之06)
- leetcode110题 题解 翻译 C语言版 Python版
- 【C++】C++中的Sequence Point,构造函数等问题
- 【day0414 C++】优先级队列 priority_queue的使用
- C语言 复制字符串 malloc
- 【day0414 C++】queue 队列的使用
- C语言 指针的深入理解