【代码随想录训练营】【Day 14】【二叉树-1】| Leetcode 94,145,144
需强化知识点
- 二叉树的前中后序遍历的迭代法
题目
144. 二叉树的前序遍历
- 注意前序的迭代法,先将root加入栈,然后先加right,后left
# 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 preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# if not root:
# return []
# val = root.val
# left = self.preorderTraversal(root.left)
# right = self.preorderTraversal(root.right)
# return [val] + left + right
if not root:
return []
stack = [root]
result = []
while stack:
node = stack.pop()
result.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
94. 二叉树的中序遍历
- 注意中序遍历,先不加入root,要使用cur一直先加入left节点,为空弹出节点,记录值和加入right节点
# 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: Optional[TreeNode]) -> List[int]:
# if not root:
# return []
# left = self.inorderTraversal(root.left)
# val = root.val
# right = self.inorderTraversal(root.right)
# return left + [val] + right
if not root:
return []
result = []
stack = []
cur = root
while cur or stack:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
result.append(cur.val)
cur = cur.right
return result
145. 二叉树的后序遍历
- 前序遍历的思路,反转的“前序遍历”(中右左),中左右 -> 左右中
# 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 postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# if not root:
# return []
# left = self.postorderTraversal(root.left)
# right = self.postorderTraversal(root.right)
# val = root.val
# return left + right + [val]
if not root:
return []
result = []
stack = [root]
while stack:
cur = stack.pop()
result.append(cur.val)
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
return result[::-1]