二叉树 02. 中序遍历
方法一:递归 时间复杂度O(N) 空间复杂度O(N)
def inorderTraversal(root): """ :type root: TreeNode :rtype: List[int] """ list1 = [] def inorder(root): if root is None: return None inorder(root.left) list1.append(root.val) inorder(root.right) inorder(root) return list1
方法二:栈 时间复杂度O(N) 空间复杂度O(N)
def inorderTraversal(root): """ :type root: TreeNode :rtype: List[int] """ if root is None: return None list1 = [] stack = [] while stack != [] or root is not None: while root is not None: # 左子树全部压栈 stack.append(root) root = root.left if stack != []: # 出栈,添加列表里,转向右子树 root = stack.pop() list1.append(root.val) root = root.right return list1

浙公网安备 33010602011771号