1.第一题
利用递归:
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res=[]
if root==None:
return []
def fn(node):
if node.left is not None:
fn(node.left)
res.append(node.val)
if node.right is not None:
fn(node.right)
fn(root)
return res
利用栈:
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if root==None:
return []
res=[]
stack=[]
curr=root
while (curr or stack):
while(curr):
stack.append(curr)
curr=curr.left
curr=stack.pop()
res.append(curr.val)
curr=curr.right
return res
利用莫里斯遍历:
算法描述如下:
算法实现:
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res=[]
current=root
temp=None
while(current):
if current.left==None:
res.append(current.val)
current=current.right
else:
node=current.left
while node.right:
node=node.right
node.right=current
temp=current
current=current.left
temp.left=None
return res