[leetcode]Binary Tree Preorder Traversal @ Python


原題地址:http://oj.leetcode.com/problems/binary-tree-preorder-traversal/

題意:這題用遞歸比較簡單。應該考察的是使用非遞歸實現二叉樹的先序遍歷。先序遍歷的遍歷順序是:根,左子樹,右子樹。

解題思路:如果樹為下圖:

                      1

                     /     \

                    2         3

                   /     \    /    \

                   4       5  6     7 

    使用一個棧。步驟為:

    一,先遍歷節點1,並入棧,如果有左孩子,繼續遍歷並入棧,一直到棧為{1,2,4}。

    二,開始彈棧,當棧頂元素為2時,彈出2,並檢測2存在右孩子5,於是遍歷5並入棧,此時棧為{1,5}。

    三,彈出5,5沒有左右孩子,繼續彈棧,將1彈出后,棧為{}。

    四,由於1存在右孩子,則繼續按照以上步驟入棧出棧。{3, 6}->{7}->{},結束。

    棧的狀態變化:{1}->{1,2}->{1,2,4}->{1,2}->{1}->{1,5}->{1}->{}->{3}->{3,6}->{3}->{}->{7}->{}。

代碼:

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of integers
    def iterative_preorder(self, root, list):
        stack = []
        while root or stack:
            if root:
                list.append(root.val)
                stack.append(root)
                root = root.left
            else:
                root = stack.pop()
                root = root.right
        return list
    
    def recursive_preorder(self, root, list):
        if root:
            list.append(root.val)
            self.preorder(root.left,list)
            self.preorder(root.right,list)

    def preorderTraversal(self,root):
        list = []
        self.iterative_preorder(root,list)
        return list
        

 


免責聲明!

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



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