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 = None

class 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.left
            if stack:
                t = stack.pop()
                root = t.right
        return ret


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM