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
相关推荐
yorushika_几秒前
python打卡训练营打卡记录day45
开发语言·python·深度学习·tensorboard
封奚泽优2 分钟前
使用Python进行函数作画
开发语言·python
fc&&fl8 分钟前
大模型面试题总结
人工智能·python
databook16 分钟前
稀疏表示与字典学习:让数据“瘦身”的魔法
python·机器学习·scikit-learn
Sheeep38 分钟前
学习Pytest + Hypothesis——能帮你发现你自己都没想到的 bug
python·测试
Once_day1 小时前
代码训练LeetCode(24)数组乘积
算法·leetcode
站大爷IP1 小时前
用Python打造办公效率神器:从数据到文档的全流程自动化实践
python
hongjianMa2 小时前
ModuleNotFoundError No module named ‘torch_geometric‘未找到
python
火兮明兮2 小时前
Python训练第四十五天
开发语言·python
zdy12635746882 小时前
python43天
python·深度学习·机器学习