给定一个二叉树的根节点root,返回它的中序遍历结果。
数据范围:树上节点数满足
,树上每个节点的值满足 
进阶:空间复杂度
,时间复杂度 )
进阶:空间复杂度
{1,2,#,#,3}[2,3,1]
{}[]
{1,2}[2,1]
{1,#,2}[1,2]
树中节点数目在范围 [0, 100] 内树中的节点的值在[-100,100]以内
class Solution: def inorderTraversal(self, root: TreeNode) -> list[int]: result = [] current = root while current: mostRight = current.left # 左子树为空,访问当前结点,移到左子树 if mostRight == None: result.append(current.val) current = current.right # 左子树不空, else: # 找到左子树的最右结点 while mostRight.right and mostRight.right != current: mostRight = mostRight.right # 最右结点的右指针空,将其指向当前结点,当前结点移到左子树 if mostRight.right == None: mostRight.right = current current = current.left # 最右结点的右指针不空(指向当前结点),将其置空,访问当前结点,移到右子树 else: mostRight.right = None result.append(current.val) current = current.right return resultMorris遍历,37ms,5176kb
class Solution: def inorderTraversal(self , root: TreeNode) -> List[int]: def dfs(root_dfs:TreeNode): if not root_dfs: return([]) return(dfs(root_dfs.left)+[root_dfs.val]+dfs(root_dfs.right)) return(dfs(root))
class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: result = [] # 用于保存中序遍历的结果 stack = [] # 辅助遍历的栈 curr = root # 当前节点初始化为根节点 while curr is not None&nbs***bsp;len(stack) > 0: # 循环条件:当前节点不为空 或者 栈不为空 while curr is not None: # 当前节点不为空时,将当前节点及其左子树节点入栈 stack.append(curr) # 将当前节点入栈 curr = curr.left # 将当前节点指向左子树节点 curr = stack.pop() # 弹出栈顶节点 result.append(curr.val) # 将弹出节点的值添加到结果列表中 curr = curr.right # 将当前节点指向弹出节点的右子树节点 return result # 返回中序遍历结果
class Solution: res = [] def inorderTraversal(self , root: TreeNode) -> List[int]: # 终止条件(当前节点为None,则停止查找) if root is None: return # 递归查找左节点(左节点同样为子树的根节点) self.inorderTraversal(root.left) if root != '#': self.res.append(root.val) # 递归查找右节点(右节点同样为子树的根节点) self.inorderTraversal(root.right) return self.res