Skip to content

Commit 291b613

Browse files
committed
[Feat] Add some tree implementation
1 parent f4e8354 commit 291b613

4 files changed

+76
-0
lines changed

112-PathSum.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
9+
if root == None:
10+
return False
11+
12+
if root.val == targetSum and root.left == None and root.right == None:
13+
return True
14+
15+
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(
16+
root.right, targetSum - root.val
17+
)

144-BinaryTreePreorderTraversal.py

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def dfs(self, root: Optional[TreeNode], result: List[int]):
9+
if root == None:
10+
return result
11+
12+
result.append(root.val)
13+
self.dfs(root.left, result)
14+
return self.dfs(root.right, result)
15+
16+
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
17+
result = []
18+
self.dfs(root, result)
19+
return result

145-BinaryTreePostorderTraversal.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def dfs(self, root: Optional[TreeNode], result: List[int]):
9+
if root == None:
10+
return result
11+
12+
self.dfs(root.left, result)
13+
self.dfs(root.right, result)
14+
result.append(root.val)
15+
return result
16+
17+
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
18+
result = []
19+
self.dfs(root, result)
20+
return result

94-BinaryTreeInorderTraversal.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def dfs(self, root: Optional[TreeNode], result: List[int]):
9+
if root == None:
10+
return result
11+
12+
self.dfs(root.left, result)
13+
result.append(root.val)
14+
self.dfs(root.right, result)
15+
return result
16+
17+
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
18+
result = []
19+
self.dfs(root, result)
20+
return result

0 commit comments

Comments
 (0)