题目:
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
链接:https://oj.leetcode.com/problems/binary-tree-preorder-traversal/
描述:二叉树的先序遍历,非递归
solution by python:
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def preorderTraversal(self, root):
if root == None: return []
stk, ans = [], []
p = root
while p!=None or len(stk)!=0:
if p == None:
p = stk.pop().right
else:
ans.append(p.val)
stk.append(p)
p = p.left
return ans