LeetCode Same Tree
2016-02-02 19:37
337 查看
LeetCode解题之Same Tree
原题
判断两棵二叉树是否相等。两棵二叉树仅在它们的形状相同且每个节点的值相等时才判为相等。注意点:
无
例子:
输入:
[code] 2 2 p = / \ q = / \ 1 3 1 3
输出: True
解题思路
树相关的问题一般用递归的方法最好理解。如果两棵树对应的节点都为空,则相等;如果值相等,那么就分别判断它们的左右子树是否相等,否则认为两棵树不相等。AC源码
[code]# 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 isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if not q and not p: return True elif not p or not q: return False elif p.val != q.val: return False else: return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) if __name__ == "__main__": None
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
相关文章推荐
- python list和dict的遍历
- 如何撤销Git的一次分支合并操作
- android Theme使用三
- Apache Spark探秘:多进程模型还是多线程模型?
- Android AdapterView View的复用机制 分析
- Hadoop-v2_streaming使用手册,简单易懂的使用手册(一)
- JEB(android app逆向)
- hdu 1056 HangOver
- .Net项目使用持续集成服务AppVeyor,Travis-CI实战
- poj2992
- poj2585 Window Pains(拓扑排序判定)
- 深入解读ESB与SOA的关系
- 深入解读ESB与SOA的关系
- 深入解读ESB与SOA的关系
- ubuntu 当中添加开机启动服务
- BestCoder Round #69 (div.2) Baby Ming and Weight lifting(hdu 5610)
- suse开启vnc远程桌面连接
- POJ2395 最小生成树prim算法
- 01背包模板
- Java本地调用JNI使用规范详解