94题 二叉树的中序遍历
1. 递归
我本来的思路就是递归。但是要注意root若为空返回空列表,不然就会产生AttributeError:
# 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 inorderTraversal(self, root: TreeNode) -> List[int]:
result = []
def dfs(root):
if not root:
return root
dfs(root.left)
result.append(root.val)
dfs(root.right)
dfs(root)
return result
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
2. 标记法
来自精选题解的大佬答案。
将树存放在栈中,0表示节点还未经过,1表示经过,经过的下一次存放入结果栈中,保证每一次都是从左子树开始,到根节点,最后到右子树。
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
stack = [(0, root)]
while stack:
thru, node = stack.pop()
if node is None:
continue
if color == 0:
stack.append((0, node.right))
stack.append((1, node))
stack.append((0, node.left))
else:
res.append(node.val)
return res
100题 相同的树
还是喜欢简单的递归表示:
# 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 isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
def dfs(root):
if not root: return [0]
return [root.val] + dfs(root.left) + dfs(root.right)
resp, resq = dfs(p), dfs(q)
return True if resp == resq else False
104题 二叉树的最大深度
还是要尽量公式化思路,而不是直接去试
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
elif not root.left and not root.right:
return 1
elif not root.left and root.right:
return 1 + self.maxDepth(root.right)
elif not root.right and root.left:
return 1 + self.maxDepth(root.left)
else:
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
101题 对称的二叉树
这道题做了好久啊,做这种题好像很可以让人开窍,不用笨办法解决问题而是真正的算法和公式来解决。比如这道题就是拿准返回True的两点:1. 左右都空 2. 左右都非空且val(根节点)相等,向内递归,看 左子树的右子树与右子树的左子树 and 左子树的左子树与右子树的右子树 两方面是否相等。(一开始做错的原因就是这步里把左右子树弄反了)
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def check(left, right):
if not left and not right: return True
elif (left and right) and (left.val == right.val):
return check(left.left, right.right) and check(left.right, right.left)
else: return False
return check(root.left, root.right)
111题 二叉树的最小深度
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
elif not root.left and not root.right:
return 1
elif root.left and not root.right:
return 1 + self.minDepth(root.left)
elif root.right and not root.left:
return 1 + self.minDepth(root.right)
else:
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))