LeetCode and LintCode: Binary Tree

Validate Binary Search Tree


Method: Traverse and Divide and Conquer.?

If it is a valid BST, use in-order traverse and get the a list. The list should be sorted unique increasing list.?

Divide and conquer: Every time, remember the minvalue, maxvalue, and isBST. Check the min, max value after the check of isBST.

Learned:

At first, I did it in a wrong way. I just compared the root value with left node value and right node value. Here is the counter example. {2, 3, 4, 1, 5, #,#}


Binary Tree Non-recursive Traversal


Pre-order Solution:

Pre-order

In-order Solution:

With Recursion: Inorder, Left, root, right. Without Recursion: Use the stack. ?Always left

Inorder

Post-order Solution:

Using Visited Flags: We will meet the root node for twice. For the first time, we need to remember we have already visited it and turn to its right node. If we meet the root node for twice, we need to push it into the result list. Here is my python code.?

Post-order:

One Stacks Methods:?Source

We use a prev variable to keep track of the previously-traversed node. Let’s assume curr is the current node that’s on top of the stack. When prev is curr' s parent, we are traversing down the tree. In this case, we try to traverse to curr' s left child if available (ie, push left child to the stack). If it is not available, we look at curr' s right child. If both left and right child do not exist (ie,curr is a leaf node), we print curr' s value and pop it off the stack. If?prev?is?curr'?s left child, we are traversing up the tree from the left. We look at?curr'?s right child. If it is available, then traverse down the right child (ie, push right child to the stack), otherwise print?curr'?s value and pop it off the stack. If?prev?is?curr'?s right child, we are traversing up the tree from the right. In this case, we print?curr'?s value and pop it off the stack.?

One Stack?

Two Stacks Method: We need to reverse the result and publish it. The order of post-order is left , right , root. So we want the reverse of post-order. So it is root, right, left. So we first visit the root, then the right, then the left. Here is the code.?


Two Stack

Printing a Binary Tree in Level Order


BFS: Using Queue. DFS: O(n), Stack We need remember the level when we push the node into the stack. Just construct a type <node, int> is enought

Printing a Binary Tree in Zig-Zag Level Order


BFS: Use the bool variable to record the order from left to right. ?DFS: Insert with level and according to even or odd.

Populating Next Right Pointers in Each Node I & II


It is easy to think of solutions for the first problem. How about the hard one? It has extra requirement: You may only use constant extra space. In such a case, we could iteratively visit the node level by level and use a needle to link them.?

Populating Next Right Pointers in Each Node II

Finding the Maximum Height of a Binary Tree


It is quite easy to use DFS recursive method to solve this problem. The hard one is to write non-recursive method. We can use BSF method. Level by level and use a counter variable to remember how many level have we visited.?

Serialization/Deserialization of Binary Tree


We can use pre-order to solve this problem. Use "#" for the NULL representation

Rebuild Binary Search Tree from Pre-order Traversal, Construct Binary Tree from Preorder and Inorder Traversal, from Inorder and Postorder Traversal.


I. This is to build BST. The difference between Binary Search Tree and Binary Tree is a binary tree where the left child contains only nodes with values less than the parent node, and where the right child only contains nodes with values greater than or equal to the parent. We pre-order is enough for us to construct tree. Method One(O(n*n)): find the index of first element which is greater than root which is the head of preorder list. Method Two(O(n)): The trick is to set a range {min .. max} for every node. Initialize the range as {INT_MIN .. INT_MAX}. The first node will definitely be in range, so create root node. To construct the left subtree, set the range as {INT_MIN …root->data}. If a values is in the range {INT_MIN .. root->data}, the values is part part of left subtree. To construct the right subtree, set the range as {root->data..max .. INT_MAX}. Method Tree(O(n)): Using a stack based on iterative solution.?

Solution

II. Always remember pre-order list[0] will remember the root of current tree. Use recursive method to construct the tree. ?

III. I really like the neat code on LeetCode. Same idea from II.

Wonderful Code


Print Edge Nodes (Boundary) of a Binary Tree


Print the left edge if it is not the leaf from top to the bottom, Print the leaf, Print the right edge if it is not the leaf from bottom to the top.

Convert Binary Search Tree to Doubly Linked List


It is actually a change of in-order non-recursive iteration.

Lowest Common Ancestor of a Binary Tree


Recursive:

Recurisve

Iterative: Find the ancestors of p and q. Compare the ancestors and you can find the lowest common ancestor. We need to find a way from root to p and to q.

Complete Binary Tree


Method1: Use bfs to visit every node. When it meet the NULL and stops. If it continue to visit the leaf and find a non-null leaf, return false.

Method2: First calculate the left edge depth. Then check the depth of last level. All nodes in the last level are as far left as possible. We need to check depth, isDecremented,?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末些侍,一起剝皮案震驚了整個濱河市姑廉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌汤徽,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,723評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件脂新,死亡現(xiàn)場離奇詭異挪捕,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)争便,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,485評論 2 382
  • 文/潘曉璐 我一進(jìn)店門级零,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人滞乙,你說我怎么就攤上這事奏纪。” “怎么了斩启?”我有些...
    開封第一講書人閱讀 152,998評論 0 344
  • 文/不壞的土叔 我叫張陵序调,是天一觀的道長。 經(jīng)常有香客問我兔簇,道長发绢,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,323評論 1 279
  • 正文 為了忘掉前任男韧,我火速辦了婚禮朴摊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘此虑。我一直安慰自己,他們只是感情好口锭,可當(dāng)我...
    茶點故事閱讀 64,355評論 5 374
  • 文/花漫 我一把揭開白布朦前。 她就那樣靜靜地躺著,像睡著了一般鹃操。 火紅的嫁衣襯著肌膚如雪韭寸。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,079評論 1 285
  • 那天荆隘,我揣著相機(jī)與錄音恩伺,去河邊找鬼。 笑死椰拒,一個胖子當(dāng)著我的面吹牛晶渠,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播燃观,決...
    沈念sama閱讀 38,389評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼褒脯,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了缆毁?” 一聲冷哼從身側(cè)響起番川,我...
    開封第一講書人閱讀 37,019評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后颁督,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體践啄,經(jīng)...
    沈念sama閱讀 43,519評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,971評論 2 325
  • 正文 我和宋清朗相戀三年沉御,在試婚紗的時候發(fā)現(xiàn)自己被綠了屿讽。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,100評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡嚷节,死狀恐怖聂儒,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情硫痰,我是刑警寧澤衩婚,帶...
    沈念sama閱讀 33,738評論 4 324
  • 正文 年R本政府宣布,位于F島的核電站效斑,受9級特大地震影響非春,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜缓屠,卻給世界環(huán)境...
    茶點故事閱讀 39,293評論 3 307
  • 文/蒙蒙 一奇昙、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧敌完,春花似錦储耐、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,289評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至晦攒,卻和暖如春闽撤,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背脯颜。 一陣腳步聲響...
    開封第一講書人閱讀 31,517評論 1 262
  • 我被黑心中介騙來泰國打工哟旗, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人栋操。 一個月前我還...
    沈念sama閱讀 45,547評論 2 354
  • 正文 我出身青樓闸餐,卻偏偏與公主長得像,于是被迫代替她去往敵國和親讼庇。 傳聞我的和親對象是個殘疾皇子绎巨,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,834評論 2 345

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