欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 144:二叉树的前序遍历

程序员文章站 2022-03-03 11:13:17
...
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def preorderTraversal(self, root):
        res = []
        stack = []
        p = root
        while(p or len(stack)):
            if p:
                res.append(p.val)
                stack.append(p)
                p = p.left
            else:
                p = stack[-1]
                stack.pop()
                p = p.right
        return res

 

相关标签: 算法 leetcode