forked from pezy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
50 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters