首页 > 编程知识 正文

二叉树遍历python代码,二叉树层序遍历递归

时间:2023-05-06 05:54:52 阅读:34464 作者:1258

迭代法遍历二叉树:左根右

# 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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。