小白一刷代码随想录(Python),主打跟上进度和学习。二刷时会回来更新博文。
本文属于个人笔记,如有问题欢迎指出。
卡哥链接
卡哥链接
前序遍历
leetcode-144
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
left = self.inorderTraversal(root.left)
right = self.inorderTraversal(root.right)
return [root.val] + left + right
中序遍历
leetcode-
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
left = self.inorderTraversal(root.left)
right = self.inorderTraversal(root.right)
return left + [root.val] + right
后序遍历
leetcode-145
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
left = self.inorderTraversal(root.left)
right = self.inorderTraversal(root.right)
return left + right + [root.val]
合并的规则是:如果两个节点重叠,那么将这两个节点的值相加作为合并后节点的新值;否则,不为 null 的节点将直接作为新二叉树的节点。返回合并后的二叉树。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if not root1:
return root2
if not root2:
return root1
head = TreeNode(root1.val + root2.val)
head.left = self.mergeTrees(root1.left, root2.left)
head.right = self.mergeTrees(root1.right, root2.right)
return head
卡哥链接
前序遍历
leetcode-144
class Solution:
def preorder(self, res, root: TreeNode):
if not root:
return
res.append(root.val)
self.preorder(res, root.left)
self.preorder(res, root.right)
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
self.preorder(res, root)
return res
中序遍历
leetcode-94
class Solution:
def inorder(self, res, root):
if not root:
return []
self.inorder(res, root.left)
res.append(root.val)
self.inorder(res, root.right)
return res
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
res = self.inorder(res, root)
return res
后序遍历
leetcode-145
class Solution:
def inorder(self, res, root):
if not root:
return []
self.inorder(res, root.left)
self.inorder(res, root.right)
res.append(root.val)
return res
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
res = self.inorder(res, root)
return res