Given a binary tree, return the preorder traversal of its nodes‘ values.
For example:
Given binary tree [1,null,2,3]
,
1 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
# 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]
"""
res = []
stack = [root]
while stack and stack[0]:
node = stack.pop()
res.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
原文地址:https://www.cnblogs.com/xiejunzhao/p/8419844.html
时间: 2024-10-11 15:53:41