二叉树leetcode思路记录
使用语言PYTHON,题目如下
一、遍历方式
1、三种遍历,前序、中序、后序(Preorder、inorder、postorder)
题目:144 前序遍历;145 后序遍历;94中序遍历
144 前序遍历
前序遍历 NLR
两种方法:recursive递归和iteratively迭代
1、recursive 递归
-建立一个helper函数:
前序遍历从Node开始,if node 确定结点是否为空
非空,append加入res
再看左看右
-使用该函数,最后return res
#recursive
def solution(not:TreeNode):
res = []
def helper(node):
if node:
res.append(node.val)
helper(node.left)
helper(node.right)
helper(root)
return res
2、Iteratively迭代
-利用Stack,LIFO
-先把root放入stack
-stack不为空时,pop出栈顶元素
-if 该 元素即 node不为空,则将其加入res中
-再看左看右,把node的左右子树加入stack,顺序为,先加入右子树,再加入左子树。重复操作
注意,该部分要先加入右子树再加入左子树,因为利用的是stack,有后进先出的特性。
class solution:
def preorderTraversal(self, root:Optional[TreeNode])->List[int]:
res = []
stack = []
stack.append(root)
while stack:
node = stack.pop()
if node:
res.append(node.val)
stack.append(node.right)
stack.append(node.left)
return res
94 中序遍历 LNR
用recursive同理
思路:helper
-节点为空,return上一节点
若不为空,按中序遍历的顺序LNR
先看左子树,将节点值加入res中,再看右子树
class solution:
res = []
def helper(root):
#base case
if not node:
return
helper(root.left)
res.append(root.val)
helper(root.right)
helper(root)
return res
迭代的 还是使用STACK,但是我个人更喜欢recursive
思路
-先判断目前stack是否为空
-把东西加入stack
-顺序LNR
把node(当前位置)加入stack,往左更新
到最左更新完后,stack pop
再将值append进res
再看右边
class solution:
stack = []
res = []
cur = root
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
res.append(cur.val)
cur = cur.right
return res
145 后序遍历LRN
-recursive
依旧使用helper 顺序为 LRN 左右中
class solution:
res = []
def helper(node):
if node:
helper(node.left)
helper(node.right)
res.append(node.val)
helper(root)
return res