赞
踩
- 输入:root = [1,null,2,3]
- 输出:[1,3,2]
-
- 输入:root = []
- 输出:[]
-
- 输入:root = [1]
- 输出:[1]
- # 递归
- class Solution:
- def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
- if not root:
- return []
- left = self.inorderTraversal(root.left)
- right = self.inorderTraversal(root.right)
- return left + [root.val] + right
- # 递归另外一种写法
- class Solution:
- def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
- def inorder(root:TreeNode):
- if not root: # 空树
- return []
- inorder(root.left)
- res.append(root.val)
- inorder(root.right)
- res = []
- inorder(root)
- return res
- # 迭代
- class Solution:
- def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
- res = []
- if not root: # 空树
- return []
- stack = [] # 隐形栈
- while stack or root:
- while root:
- stack.append(root) # 节点入栈
- root = root.left
- root = stack.pop() # 节点弹栈
- res.append(root.val)
- root = root.right
- return res
- # 迭代另外一种写法
- class Solution:
- def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
- stack = []
- def add_all_left(node):
- while node:
- stack.append(node)
- node = node.left
- res = []
- add_all_left(root)
- while stack:
- node = stack.pop()
- res.append(node.val)
- add_all_left(node.right)
- return res
- # Morris 中序遍历
- class Solution:
- def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
- res = []
- while root:
- if root.left:
- predecessor = root.left
- while predecessor.right:
- predecessor = predecessor.right
- predecessor.right = root
- temp = root
- root = root.left
- temp.left = None
- else:
- res.append(root.val)
- root = root.right
- return res
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。