迭代法遍历二叉树:左根右
# definitionforabinarytreenode.# class treenode : # def _ init _ (self,val=0,left=None, right=none (3360 # self.val=val # self.left=left # self.right=rightclasssolution 3360 definordertraversal ) SELT : if not root : return [ ]堆栈=[ root ] #带有左侧子树的根节点numarrray=[]while )堆栈!=[] ) :root=stack.pop(while ) root.leftorroot.right ) 3360#当前节点上有子节点的while ) root.left ) 3360#左节点存在避免重复遍历(root=p if root.right: # )当前节点中不存在左节点,但存在右节点numar rray.append (root.val )。 输出当前节点的root=root往右走,numarrray.append(root.val )当前节点是一个子节点,直接输出返回编号rray