173. Binary Search Tree Iterator

173. Binary Search Tree Iterator

題目:
https://leetcode.com/problems/binary-search-tree-iterator/

難度:
Medium

同樣沒(méi)有聽(tīng)題目要求,一開(kāi)始就取巧,用InOrder,這樣得到BSF有序排列,然后使用


class BSTIterator(object):
    def __init__(self, root):
        """
        :type root: TreeNode
        """
        self.root = root
        self.lst = []
        self.inOrder(root)
        self.lst.reverse()
            
        

    def hasNext(self):
        """
        :rtype: bool
        """
        return self.lst != []
        

    def next(self):
        """
        :rtype: int
        """
        return self.lst.pop()
    
    def inOrder(self, root):
        if root == None:
            return
        self.inOrder(root.left)
        self.lst.append(root.val)
        self.inOrder(root.right)
        

谷歌了一下,得到如何滿足題目要求的hint,從root開(kāi)始,往左走,把左孩子壓入stack,直到左邊為空。

然后開(kāi)始取node,如果node有右孩子,則同樣要把node的左孩子入stack,畫了一個(gè)圖,可行。


class BSTIterator(object):
    def __init__(self, root):
        """
        :type root: TreeNode
        """
        self.root = root
        self.stack = []
        self.pushLeft(root)
        

    def hasNext(self):
        """
        :rtype: bool
        """
        return self.stack != []
        

    def next(self):
        """
        :rtype: int
        """
        while self.hasNext():
            cur = self.stack.pop()
            if cur.right:
                self.pushLeft(cur.right)
            return cur.val
            
    def pushLeft(self, node):
        """
        :type node: TreeNode
        """
        cur = node
        while cur:
            self.stack.append(cur)
            cur = cur.left
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容