LintCode-二叉樹的前呵曹、中、后序遍歷-遞歸

描述

給出一棵二叉樹何暮,返回其節(jié)點(diǎn)值的前奄喂、中、后序遍歷跨新。

樣例

給出一棵二叉樹 {1,#,2,3},

1

2
/
3
返回 [3,2,1]

挑戰(zhàn)

你能使用非遞歸實(shí)現(xiàn)么?

代碼(遞歸)

前序遍歷

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: A Tree
    @return: Preorder in ArrayList which contains node values.
    """
    def preorderTraversal(self, root):
        # write your code here
        result = []
        if root is None:
            return result
        queue = [root]
        while queue:
            root = queue.pop()
            result.append(root.val)
            if root.right is not None:
                queue.append(root.right)
            if root.left is not None:
                queue.append(root.left)
        return result

中序遍歷
第一種寫法

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: A Tree
    @return: Inorder in ArrayList which contains node values.
    """
    def inorderTraversal(self, root):
        # write your code here
        if root is None:
            return []
        stack = [root]
        result = []
        while stack:
            new_root = stack.pop()
            if new_root.left is not None:
                stack.append(new_root)
                stack.append(new_root.left)
                continue
            else:
                result.append(new_root.val)
                while new_root.right is None:
                    try:
                        new_root = stack.pop()
                    except IndexError:
                        return result
                    result.append(new_root.val)
                stack.append(new_root.right)
        return result
                    

第二種寫法

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: A Tree
    @return: Inorder in ArrayList which contains node values.
    """
    def inorderTraversal(self, root):
        # write your code here
        if root is None:
            return []
        stack = [root]
        result = []
        while stack:
            new_root = stack[-1]
            if new_root.left is None and new_root.right is None:
                result.append(new_root.val)
                stack.pop()
                while stack:
                    new_root = stack.pop()
                    result.append(new_root.val)
                    if new_root.right is not None:
                        stack.append(new_root.right)
                        break
            else:
                if new_root.left is not None:
                    stack.append(new_root.left)
                else:
                    if new_root.right is not None:
                        stack.pop()
                        result.append(new_root.val)
                        stack.append(new_root.right)
        return result
                    

后序遍歷

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: A Tree
    @return: Postorder in ArrayList which contains node values.
    """
    def postorderTraversal(self, root):
        # write your code here
        result = []
        if root is None:
            return result                                       
        stack = [root]
        already = []
        while stack:
            new_root = stack.pop()
            if new_root in already:
                result.append(new_root.val)
                continue
            if new_root.left is None and new_root.right is None:
                result.append(new_root.val)
            else:
                stack.append(new_root)
                already.append(new_root)
            if new_root.right is not None:
                stack.append(new_root.right)
            if new_root.left is not None:
                stack.append(new_root.left)
        return result
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末陋率,一起剝皮案震驚了整個(gè)濱河市瓦糟,隨后出現(xiàn)的幾起案子菩浙,更是在濱河造成了極大的恐慌,老刑警劉巖先嬉,帶你破解...
    沈念sama閱讀 216,651評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異衅胀,居然都是意外死亡滚躯,警方通過查閱死者的電腦和手機(jī)掸掏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門茄唐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來呼盆,“玉大人访圃,你說我怎么就攤上這事腿时「窳耍” “怎么了盛末?”我有些...
    開封第一講書人閱讀 162,931評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長檐嚣。 經(jīng)常有香客問我净嘀,道長挖藏,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,218評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮辟躏,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘裹匙。我一直安慰自己籽御,他們只是感情好铃将,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,234評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般弧哎。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上序攘,一...
    開封第一講書人閱讀 51,198評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音瞄沙,去河邊找鬼。 笑死垫桂,一個(gè)胖子當(dāng)著我的面吹牛诬滩,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播愚臀,決...
    沈念sama閱讀 40,084評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼欣鳖!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起怀酷,我...
    開封第一講書人閱讀 38,926評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎样眠,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體厢塘,經(jīng)...
    沈念sama閱讀 45,341評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡喂急,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,563評(píng)論 2 333
  • 正文 我和宋清朗相戀三年狡孔,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,731評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖完沪,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情宽档,我是刑警寧澤偿短,帶...
    沈念sama閱讀 35,430評(píng)論 5 343
  • 正文 年R本政府宣布篷朵,位于F島的核電站笔链,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏坪创。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,036評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望肩狂。 院中可真熱鬧,春花似錦、人聲如沸态蒂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春鸯乃,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背奖年。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留猩系,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,743評(píng)論 2 368
  • 正文 我出身青樓咱扣,卻偏偏與公主長得像沪铭,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子驮肉,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,629評(píng)論 2 354

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