File tree 3 files changed +50
-1
lines changed
3 files changed +50
-1
lines changed Original file line number Diff line number Diff line change
1
+ # 思路(C++)
2
+
1
3
这道题没啥好说的,太简单了,尤其是刚做过昨天那道。我几乎直接在LeetCode上写下了答案,连本地编译都没用,抱着试试运气的心态,竟直接AC了。
2
4
花了不到3分钟。
3
5
4
6
递归还是那个递归,门口有一颗二叉树,另一颗也是二叉树。它们长得一样不?从根开始看呗。好无聊。
7
+
8
+ ## Python
9
+
10
+ 值得注意的是,Python 里更习惯用 ` is ` 来比较,如果只是判断非零(有效)时,可以直接用 ` if p: ` 这样更简洁的方式。
11
+
12
+ 参考:< https://stackoverflow.com/questions/7816363/if-a-vs-if-a-is-not-none >
Original file line number Diff line number Diff line change
1
+ #!python3
2
+
3
+
4
+ class TreeNode :
5
+ def __init__ (self , x ):
6
+ self .val = x
7
+ self .left = None
8
+ self .right = None
9
+
10
+
11
+ class Solution :
12
+ def isSameTree (self , p , q ):
13
+ """
14
+ :type p: TreeNode
15
+ :type q: TreeNode
16
+ :rtype: bool
17
+ """
18
+ if p and q :
19
+ return p .val == q .val and self .isSameTree (p .left , q .left ) and self .isSameTree (p .right , q .right )
20
+ return p is q
21
+
22
+
23
+ if __name__ == "__main__" :
24
+ example1 = TreeNode (1 )
25
+ example1 .left = TreeNode (2 )
26
+ example1 .right = TreeNode (3 )
27
+ assert (Solution ().isSameTree (example1 , example1 ) is True )
28
+
29
+ example2l = TreeNode (1 )
30
+ example2l .left = TreeNode (2 )
31
+ example2r = TreeNode (1 )
32
+ example2r .right = TreeNode (2 )
33
+ assert (Solution ().isSameTree (example2l , example2r ) is False )
34
+
35
+ example3l = TreeNode (1 )
36
+ example3l .left = TreeNode (2 )
37
+ example3l .right = TreeNode (1 )
38
+ example3r = TreeNode (1 )
39
+ example3r .left = TreeNode (1 )
40
+ example3r .right = TreeNode (2 )
41
+ assert (Solution ().isSameTree (example3l , example3r ) is False )
Original file line number Diff line number Diff line change @@ -7,7 +7,7 @@ LeetCode solutions in C++ 11. (From Easy to Hard)
7
7
| ---| -----| --------| --------| ----------|
8
8
| 1| [ Single Number] [ 1 ] | [ C++] ( 001.%20Single%20Number/solution.h ) | ; [ Python] ( 001.%20Single%20Number/solution.py ) | 2014/10/15| Medium|
9
9
| 2| [ Maximum Depth of Binary Tree] [ 2 ] | [ C++] ( 002.%20Maximum%20Depth%20of%20Binary%20Tree/solution.h ) | ; [ Python] ( 002.%20Maximum%20Depth%20of%20Binary%20Tree/solution.py ) | 2014/10/16| Easy|
10
- | 3| [ Same Tree] [ 3 ] | [ C++] ( 003.%20Same%20Tree/solution.h ) | 2014/10/17| Easy|
10
+ | 3| [ Same Tree] [ 3 ] | [ C++] ( 003.%20Same%20Tree/solution.h ) &# 124 ; [ Python ] ( 003.%20Same%20Tree/solution.py ) | 2014/10/17| Easy|
11
11
| 4| [ Reverse Integer] [ 4 ] | [ C++] ( 004.%20Reverse%20Integer/solution.h ) | 2014/10/18| Easy|
12
12
| 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|
13
13
| 6| [ Unique Binary Search Trees] [ 6 ] | [ C++] ( 006.%20Unique%20Binary%20Search%20Trees/solution.h ) | 2014/10/20| Medium|
You can’t perform that action at this time.
0 commit comments