144. Binary Tree Preorder Traver
# 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):
"""
:type root: TreeNode
:rtype: List[int]
"""
#use the LIFO feature of stack,
#if the node is not empty, output the value, then first put right node into stack, then put left node into stack
#next loop will read the left node first, after finish interating the left node, it will pop the right node and iterate the right node.
res=[]
stack=[root]
while stack:
node=stack.pop()
if node:
res.append(node.val)
stack.append(node.right)
stack.append(node.left)
return res
本文标题:144. Binary Tree Preorder Traver
本文链接:https://www.haomeiwen.com/subject/xcyomttx.html
网友评论