标签:return sel 简单 递归 入栈 循环 treenode type tree
二叉树的先序遍历(非递归)特别简单
直接上代码,根节点先入栈,然后循环栈不为空,pop出来后让右节点和左节点分别入栈
# 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] """ if root==None: return [] stack=[root] result=[] while len(stack)!=0: cur=stack.pop() result.append(cur.val) if cur.right!=None: stack.append(cur.right) if cur.left!=None: stack.append(cur.left) return result
标签:return sel 简单 递归 入栈 循环 treenode type tree
原文地址:https://www.cnblogs.com/hit-joseph/p/9452531.html