Skip to content

Commit

Permalink
added python for 003.
Browse files Browse the repository at this point in the history
  • Loading branch information
pezy committed Dec 14, 2017
1 parent 1ec1078 commit 38e99bc
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
8 changes: 8 additions & 0 deletions 003. Same Tree/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
# 思路(C++)

这道题没啥好说的,太简单了,尤其是刚做过昨天那道。我几乎直接在LeetCode上写下了答案,连本地编译都没用,抱着试试运气的心态,竟直接AC了。
花了不到3分钟。

递归还是那个递归,门口有一颗二叉树,另一颗也是二叉树。它们长得一样不?从根开始看呗。好无聊。

## Python

值得注意的是,Python 里更习惯用 `is` 来比较,如果只是判断非零(有效)时,可以直接用 `if p:` 这样更简洁的方式。

参考:<https://stackoverflow.com/questions/7816363/if-a-vs-if-a-is-not-none>
41 changes: 41 additions & 0 deletions 003. Same Tree/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#!python3


class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None


class Solution:
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p is q


if __name__ == "__main__":
example1 = TreeNode(1)
example1.left = TreeNode(2)
example1.right = TreeNode(3)
assert(Solution().isSameTree(example1, example1) is True)

example2l = TreeNode(1)
example2l.left = TreeNode(2)
example2r = TreeNode(1)
example2r.right = TreeNode(2)
assert(Solution().isSameTree(example2l, example2r) is False)

example3l = TreeNode(1)
example3l.left = TreeNode(2)
example3l.right = TreeNode(1)
example3r = TreeNode(1)
example3r.left = TreeNode(1)
example3r.right = TreeNode(2)
assert(Solution().isSameTree(example3l, example3r) is False)
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ LeetCode solutions in C++ 11. (From Easy to Hard)
|---|-----|--------|--------|----------|
|1|[Single Number][1]|[C++](001.%20Single%20Number/solution.h)&#124;[Python](001.%20Single%20Number/solution.py)|2014/10/15|Medium|
|2|[Maximum Depth of Binary Tree][2]|[C++](002.%20Maximum%20Depth%20of%20Binary%20Tree/solution.h)&#124;[Python](002.%20Maximum%20Depth%20of%20Binary%20Tree/solution.py)|2014/10/16|Easy|
|3|[Same Tree][3]|[C++](003.%20Same%20Tree/solution.h)|2014/10/17|Easy|
|3|[Same Tree][3]|[C++](003.%20Same%20Tree/solution.h)&#124;[Python](003.%20Same%20Tree/solution.py)|2014/10/17|Easy|
|4|[Reverse Integer][4]|[C++](004.%20Reverse%20Integer/solution.h)|2014/10/18|Easy|
|5|[Best Time to Buy and Sell Stock II][5]|[C++](005.%20Best%20Time%20to%20Buy%20and%20Sell%20Stock%20II/solution.h)|2014/10/19|Medium|
|6|[Unique Binary Search Trees][6]|[C++](006.%20Unique%20Binary%20Search%20Trees/solution.h)|2014/10/20|Medium|
Expand Down

0 comments on commit 38e99bc

Please sign in to comment.