Binary Tree Traversal (Pre-order, In-order, Post-order)

樹的三種DFS遍歷,是指按照根節(jié)點(diǎn)(自己)被訪問(wèn)的順序

  1. Pre-Order: 先訪問(wèn)根節(jié)點(diǎn)翩伪,再訪問(wèn)其左右子樹着倾。對(duì)每一個(gè)subtree,同樣適用组去。
  2. In-Order: 先訪問(wèn)其左,再中間步淹,再右子樹从隆。對(duì)每一個(gè)subtree缭裆,同樣適用键闺。
  3. Post-Order: 先訪問(wèn)其左右子樹,再中間澈驼。對(duì)每一個(gè)subtree辛燥,同樣適用。
image.png

Pre-Order Traversal

三種解法:

  1. Recursive
  2. Iterate 用Stack
  3. Morris Traversal (好處是盅藻,Pre-Order和In-Order代碼只有很小的改動(dòng))
Morris Pre-Order Traversal (LeetCode 144) (Medium)

1...If left child is null, print the current node data. Move to right child.
….Else, Make the right child of the inorder predecessor point to the current node. Two cases arise:
………a) The right child of the inorder predecessor already points to the current node. Set right child to NULL. Move to right child of current node.
………b) The right child is NULL. Set it to current node. Print current node’s data and move to left child of current node.
2...Iterate until current node is not NULL.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new LinkedList<> ();
        
        TreeNode current = root;
        TreeNode prev    = null;
        
        while (current != null) {
            if (current.left == null) {
                result.add (current.val);
                current = current.right;
            } else { // has left, then find the rightmost of left subtree and connect to current
                
                prev = current.left;
                while (prev.right != null && prev.right != current) {
                    prev = prev.right;
                }
                
                // difference from in-order: print current first 
                if (prev.right == null) {
                    result.add (current.val);
                    
                    prev.right = current;
                    current    = current.left;
                } else {
                    prev.right = null;
                    current    = current.right;
                }   
            }
        }
        
        return result;
    }
}
Morris In-Ordere Traversal (LeetCode 94) (Medium)
  1. Initialize current as root
  2. While current is not NULL
    If current does not have left child
    a) Print current’s data
    b) Go to the right, i.e., current = current->right
    Else
    a) Make current as right child of the rightmost
    node in current's left subtree
    b) Go to this left child, i.e., current = current->left
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new LinkedList<> ();
        
        TreeNode current = root;
        TreeNode prev    = null;
        
        while (current != null) {
            // left first
            if (current.left == null) {
                result.add (current.val);
                current = current.right;
            }
            
            // if there is left, get the rightmost node of left subtree and connect back to current
            else {
                prev = current.left;
                
                // 1. get previous node
                // because the prev.right might connected to current already
                // need to stop in this case
                while (prev.right != null && prev.right != current) { 
                    prev = prev.right;
                }
                
                // 2. if previous hasnt connected to current
                if (prev.right == null) {
                    prev.right = current;
                    current = current.left;
                }
                
                // 3. if previous already connected to current, and while traverse current node
                // has been visited (only after visited current, we can get the prev)
                else if (prev.right == current) {
                    // revert the tree modification
                    prev.right = null;
                    
                    result.add (current.val);
                    current = current.right;
                }
            }
        }
        
        return result;
    }
}

Stack Inorder

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        if (root == null)
            return new ArrayList<Integer> ();
        
        TreeNode currentNode = root;
        Stack<TreeNode> tracker = new Stack<> ();
        List<Integer> result = new ArrayList<> ();
        
        while (currentNode != null || !tracker.isEmpty ()) {
            while (currentNode != null) {
                tracker.push (currentNode);
                currentNode = currentNode.left;
            }
            
            TreeNode current = tracker.pop ();
            result.add (current.val);
            currentNode = current.right;
        }
        
        return result;
    }
}
Post-Order Traversal** (LeetCode 145) (Hard)

Recursive Solution

  1. 用reversed post -order traversal
  2. While root is not EMPTY
    • Pop the first element from the stack and push it into a List
    • reverse_post (root.right)
    • reverse_post (root.left)
  3. reverse (the result List) === > 就是最后post - order的結(jié)果

Stack Solution

while not stack.empty()
    root = stack.pop ()
    print (root.val)
    stack.push (root.left)
    stack.push (root.right)

reverse (output)

Note:
實(shí)現(xiàn)的時(shí)候购桑,不需要最后翻轉(zhuǎn),可以在用Deque來(lái)存儲(chǔ)Result List氏淑,加入的時(shí)候AddFirst.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        Deque<Integer> result = new LinkedList<> ();
        if (root == null) {
            return new ArrayList (result);
        }
        
        Stack <TreeNode> tracker = new Stack <> ();
        tracker.push (root);
        
        while (!tracker.isEmpty ()) {
            TreeNode node = tracker.pop ();
            result.addFirst (node.val);
            
            if (node.left != null)
                tracker.push (node.left);
            
            if (node.right != null)
                tracker.push (node.right);
        }
        
        return new ArrayList(result);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末勃蜘,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子假残,更是在濱河造成了極大的恐慌缭贡,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,265評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件辉懒,死亡現(xiàn)場(chǎng)離奇詭異阳惹,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)眶俩,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,078評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門莹汤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人颠印,你說(shuō)我怎么就攤上這事纲岭∧ㄖ瘢” “怎么了?”我有些...
    開封第一講書人閱讀 156,852評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵止潮,是天一觀的道長(zhǎng)窃判。 經(jīng)常有香客問(wèn)我,道長(zhǎng)喇闸,這世上最難降的妖魔是什么袄琳? 我笑而不...
    開封第一講書人閱讀 56,408評(píng)論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮燃乍,結(jié)果婚禮上唆樊,老公的妹妹穿的比我還像新娘。我一直安慰自己橘沥,他們只是感情好窗轩,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,445評(píng)論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著座咆,像睡著了一般。 火紅的嫁衣襯著肌膚如雪仓洼。 梳的紋絲不亂的頭發(fā)上介陶,一...
    開封第一講書人閱讀 49,772評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音色建,去河邊找鬼哺呜。 笑死,一個(gè)胖子當(dāng)著我的面吹牛箕戳,可吹牛的內(nèi)容都是我干的某残。 我是一名探鬼主播,決...
    沈念sama閱讀 38,921評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼陵吸,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼玻墅!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起壮虫,我...
    開封第一講書人閱讀 37,688評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤澳厢,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后囚似,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體剩拢,經(jīng)...
    沈念sama閱讀 44,130評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,467評(píng)論 2 325
  • 正文 我和宋清朗相戀三年饶唤,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了徐伐。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,617評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡募狂,死狀恐怖办素,靈堂內(nèi)的尸體忽然破棺而出角雷,到底是詐尸還是另有隱情,我是刑警寧澤摸屠,帶...
    沈念sama閱讀 34,276評(píng)論 4 329
  • 正文 年R本政府宣布谓罗,位于F島的核電站,受9級(jí)特大地震影響季二,放射性物質(zhì)發(fā)生泄漏檩咱。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,882評(píng)論 3 312
  • 文/蒙蒙 一胯舷、第九天 我趴在偏房一處隱蔽的房頂上張望刻蚯。 院中可真熱鬧,春花似錦桑嘶、人聲如沸炊汹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,740評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)讨便。三九已至,卻和暖如春以政,著一層夾襖步出監(jiān)牢的瞬間霸褒,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,967評(píng)論 1 265
  • 我被黑心中介騙來(lái)泰國(guó)打工盈蛮, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留废菱,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,315評(píng)論 2 360
  • 正文 我出身青樓抖誉,卻偏偏與公主長(zhǎng)得像殊轴,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子袒炉,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,486評(píng)論 2 348

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

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,308評(píng)論 0 10
  • 春雨冷蕭蕭旁理, 風(fēng)密斜織到。 惹起枝涼鳥難棲梳杏, 寒氣傷花俏韧拒。 早卸薄毛衣, ...
    大魚奶奶閱讀 336評(píng)論 0 2
  • 倒掛在天上的海 平靜不泛一絲漣漪 就像墻上的畫 把我深深吸引 那一刻 仿佛羽化的我 兩只飛鳥打破了寧?kù)o 讓畫面鮮活...
    柏淺歌閱讀 393評(píng)論 2 11
  • O圈O閱讀 227評(píng)論 0 0