Leetcode 144:二叉树的前序遍历

# 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)