Python实现二叉树的非递归先序遍历
生活随笔
收集整理的這篇文章主要介紹了
Python实现二叉树的非递归先序遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
思路:
1. 使用列表保存結果;
2. 使用棧(列表實現)存儲結點;
3. 當根結點存在,保存結果,根結點入棧;
4. 將根結點指向左子樹;
5. 根結點不存在,棧頂元素出棧,并將根結點指向棧頂元素的右子樹;
6. 重復步驟3-6,直到棧空。
LeetCode: 144. Binary Tree Preorder Traversal
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution(object):def preorderTraversal(self, root):""":type root: TreeNode:rtype: List[int]"""ret = []stack = []while root or stack:while root:ret.append(root.val)stack.append(root)root = root.leftif stack:t = stack.pop()root = t.rightreturn ret轉載于:https://www.cnblogs.com/qiaojushuang/p/7862930.html
總結
以上是生活随笔為你收集整理的Python实现二叉树的非递归先序遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qemu 简述
- 下一篇: python 关于字节串和字符串