Leetcode 144. 二叉树的前序遍历 python

给定一个二叉树,返回它的 前序 遍历。

示例:

输入: [1,null,2,3]
1

2
/
3

输出: [1,2,3]

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        result=[]

        if(root==None):
            return result
        stack=list()
        stack.append(root)
        while(len(stack)!=0):
            top=stack.pop()
            if(top.right!=None):
                stack.append(top.right)
            if(top.left!=None):
                stack.append(top.left)
            result.append(top.val)
        return result
        

你可能感兴趣的:(LeetCode)