leetcode-94:二叉樹的中序遍歷
阿新 • • 發佈:2021-02-10
技術標籤:演算法python二叉樹leetcode演算法python資料結構
LC 二叉樹的中序遍歷
題目
給定一個二叉樹的根節點 root ,返回它的 中序 遍歷。
示例 1:
輸入:root = [1,null,2,3]
輸出:[1,3,2]
示例 2:
輸入:root = []
輸出:[]
示例 3:
輸入:root = [1]
輸出:[1]
示例 4:
輸入:root = [1,2]
輸出:[2,1]
示例 5:
輸入:root = [1,null,2]
輸出:[1,2]
解題:
方法一:遞迴
# 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]:
def inorder(root):
if not root:
return
inorder(root.left)
res.append(root.val)
inorder(root.right)
res = []
inorder(root)
return res
可以找到規律,將先序遍歷改成中序遍歷只需要將res.append(root.val)
放到中間即可
方法二:迭代
# 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]:
if not root:
return []
cur,stack,res = root,[],[]
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
res.append(cur.val)
cur = cur.right
return res