Python | Leetcode Python题解之第144题二叉树的前序遍历

题目:

题解:

python 复制代码
class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        res = list()
        if not root:
            return res
        
        p1 = root
        while p1:
            p2 = p1.left
            if p2:
                while p2.right and p2.right != p1:
                    p2 = p2.right
                if not p2.right:
                    res.append(p1.val)
                    p2.right = p1
                    p1 = p1.left
                    continue
                else:
                    p2.right = None
            else:
                res.append(p1.val)
            p1 = p1.right
        
        return res
相关推荐
sonrisa_8 分钟前
collections模块
python
折翼的恶魔12 分钟前
数据分析:排序
python·数据分析·pandas
天雪浪子30 分钟前
Python入门教程之赋值运算符
开发语言·python
站大爷IP1 小时前
5个技巧写出专业Python代码:从新手到进阶的实用指南
python
_不会dp不改名_1 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
hrrrrb1 小时前
【Python】字符串
java·前端·python
大翻哥哥2 小时前
Python 2025:低代码开发与自动化运维的新纪元
运维·python·低代码
吃着火锅x唱着歌2 小时前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun2 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌2 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode