File tree 2 files changed +56
-0
lines changed
0094.Binary Tree Inorder Traversal
0096.Unique Binary Search Trees
2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Definition for a binary tree node.
2
+ # class TreeNode:
3
+ # def __init__(self, x):
4
+ # self.val = x
5
+ # self.left = None
6
+ # self.right = None
7
+
8
+ # 递归版本
9
+ """
10
+ class Solution:
11
+ def inorderTraversal(self, root):
12
+ """
13
+ : type root : TreeNode
14
+ : rtype : List [int ]
15
+ """
16
+ def dp(node):
17
+ if not node:
18
+ return
19
+ dp(node.left)
20
+ ls.append(node.val)
21
+ dp(node.right)
22
+ ls=[]
23
+ dp(root)
24
+ return ls
25
+ """
26
+
27
+ # 非递归版本
28
+ class Solution :
29
+ def inorderTraversal (self , root ):
30
+ """
31
+ :type root: TreeNode
32
+ :rtype: List[int]
33
+ """
34
+ ls = []
35
+ stack = []
36
+ while root or stack :
37
+ while root :
38
+ stack .append (root )
39
+ root = root .left
40
+ if stack :
41
+ root = stack .pop (- 1 )
42
+ ls .append (root .val )
43
+ root = root .right
44
+ return ls
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def numTrees (self , n ):
3
+ """
4
+ :type n: int
5
+ :rtype: int
6
+ """
7
+ res = [0 ] * (n + 1 )
8
+ res [0 ] = 1
9
+ for i in range (1 , n + 1 ):
10
+ for j in range (i ):
11
+ res [i ] += res [j ] * res [i - j - 1 ]
12
+ return res [n ]
You can’t perform that action at this time.
0 commit comments