classSolution: definorderTraversal(self, root: TreeNode) -> List[int]: cur = root #借助临时的cur,不要修改root res = [] stack = [] while cur or stack: if cur: # 一直往左走,全部入栈 stack.append(cur) cur = cur.left else: # 取出栈顶节点,处理,再处理该节点的右子树 cur = stack.pop() res.append(cur.val) cur = cur.right return res
前序遍历
写法一
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defpreorderTraversal(self, root: TreeNode) -> List[int]: cur = root res = [] stack = [] while cur or stack: if cur: stack.append(cur) # 每一个节点都放入栈中 res.append(cur.val) cur = cur.left else: cur = stack.pop() # 这里pop出来的是已经访问过的节点 cur = cur.right # 还需要指向右子树 return res