二叉树
36. 二叉树的中序遍历
递归就不写了,写一下迭代法
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return
res = []
cur = root
stack = []
while cur or stack:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
res.append(cur.val)
cur = cur.right
return res
顺便再写一下前序和后序的迭代法
前序:
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return
st = [root]
res = []
# cur =
while st:
cur = st.pop()
res.append(cur.val)
if cur.right:
st.append(cur.right)
if cur.left:
st.append(cur.left)
return res
后序:
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return
cur = root
st = []
prev = None
res = []
while st or cur:
if cur:
st.append(cur)
cur = cur.left
else:
cur = st.pop()
#现在需要确定的是是否有右子树,或者右子树是否访问过
#如果没有右子树,或者右子树访问完了,也就是上一个访问的节点是右子节点时
#说明可以访问当前节点
if not cur.right or cur.right == prev:
res.append(cur.val)
prev = cur
cur = None
else:
st.append(cur)
cur = cur.right
return res
37. 二叉树的最大深度
分解很简单,直接交给递归函数。但是遍历的思路都要会
- 分解(动态规划思路)
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
- 遍历(回溯思路)
走完之后depth-1
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def helper(root):
if not root:
self.res = max(self.res, self.depth)
return
self.depth += 1
helper(root.left)
helper(root.right)
self.depth -= 1
self.depth = 0
self.res = 0
helper(root)
return self.res
- 延伸:可否不用递归来做这道题?
这个解法是chatgpt写的,将depth和node一起压入栈,避免对depth +1, -1的操作
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
stack = [(root, 1)]
max_depth = 0
while stack:
node, depth = stack.pop()
if node:
max_depth = max(max_depth, depth)
if node.right:
stack.append((node.right, depth + 1))
if node.left:
stack.append((node.left, depth + 1))
return max_depth
- 反转二叉树
递归函数的定义:给定二叉树根节点,反转它的左右子树。
后续位置递归
class Solution(object):