ZXAlgorithm - C3 Binary Tree & Divide Conquer

Think the relationships between the root and childs
DC or traverse/ use class ResultType
Binary tree traversal: pre/in/post
Use DC or traverse to solve problem
Binary search tree: inorder is non-descending sequence
Quick and Merge sort: Space vs Stable
脉络是什么?
探究时间复杂度,二叉树的遍历,二叉树的DFS包括遍历,分治,非递归遍历分治,二叉搜索树

1 Time complexity II

T(n) = 2T(n/2) + O(n) = n + nlogn
T(n) = 2T(n/2) + O(1) ~= n + 2n = O(n) binary tree are almost all O(n)

2 二叉树的遍历Traverse in Binary Tree: preorder, inorder, postorder

3 DFS in Binary Tree

要点

  • Traverse vs DC:
    Recursion is method vs Traverse and DC are algorithm or idea realized by recursion
    Result in parameter traverse vs Result in return value dc
    Top down vs Bottom up
    Traverse is changing parameters vs DC return the outcome, not change given parameter
  • Recursion vs non-recursion
    Non-recursion is using stack to simulate recursion
    Ourselves stack is heap memory ~= memory size(like 1/64-1/4 for server, 4M-64M for client)
    Stack memory ~= process memory allocated for each program and is not enough(like 512K)
  • Recursion 3 essentials SDE
    Definition: get what param return what param
    Division:
    Exit: check null or leaves


  • 核心
    Think the relationship between the result of the whole problem and two children
    Use class result type

3.1 Samples

Maximum Depth of binary tree
https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
http://www.lintcode.com/problem/maximum-depth-of-binary-tree/
https://www.jiuzhang.com/solutions/maximum-depth-of-binary-tree/
Process: Math.max(,) + 1
Binary tree paths
https://leetcode.com/problems/binary-tree-paths/description/
https://www.jiuzhang.com/solution/binary-tree-paths/
https://www.jiuzhang.com/solution/binary-tree-paths/#tag-highlight-lang-python
https://leetcode.com/problems/binary-tree-paths/discuss/68272/Python-solutions-(dfs%2Bstack-bfs%2Bqueue-dfs-recursively).
Test: null
Initial: List<S> paths
Process: add left path, add right path, if it is leaf, add one node,"" + root.val change it into node
Minimum Subtree
http://www.lintcode.com/en/problem/minimum-subtree/ http://www.jiuzhang.com/solutions/minimum-subtree/
用一个变量存最小的树和权重

3.2 Result Type

Balanced Binary Tree
https://leetcode.com/problems/balanced-binary-tree/
https://leetcode.com/problems/balanced-binary-tree/discuss/35708/VERY-SIMPLE-Python-solutions-(iterative-and-recursive)-both-beat-90
http://www.lintcode.com/problem/balanced-binary-tree/ http://www.jiuzhang.com/solutions/balanced-binary-tree/

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        self.is_balanced = True
        self.helper(root)
        return self.is_balanced
        
        
    def helper(self, root):
        if not self.is_balanced:
            return 0
        if not root:
            return 0
        left_height = self.helper(root.left)
        right_height = self.helper(root.right)
        if abs(left_height - right_height) > 1:
            self.is_balanced = False
        return 1+max(left_height, right_height)

我感觉我的写法也挺简洁的,最重要的是理解traverse和DC的区别,参数是存在返回值里还是存在变量里
Subtree with Maximum Average
http://www.lintcode.com/problem/subtree-with-maximum-average/ http://www.jiuzhang.com/solutions/subtree-with-maximum-average/

class Solution:
    """
    @param root: the root of binary tree
    @return: the root of the maximum average of subtree
    """
    def findSubtree2(self, root):
        # write your code here
        self.max_avg = float('-inf')
        self.max_avg_tree = None
        self.helper(root)
        return self.max_avg_tree
        
    def helper(self, root):
        if not root:
            return 0, 0

        left_weight, left_size = self.helper(root.left)
        right_weight, right_size = self.helper(root.right)
        weight = left_weight + right_weight + root.val
        size = left_size + right_size + 1
        avg = weight / size
        if avg > self.max_avg:
            self.max_avg_tree = root
            self.max_avg = avg
        
        return weight, size

Lowest Common Ancestor
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
http://www.lintcode.com/problem/lowest-common-ancestor/
http://www.jiuzhang.com/solutions/lowest-common-ancestor/
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/158060/Python-DFS-tm
with parent pointer vs no parent pointer follow up: LCA II & III

3.3 Binary Search Tree

什么是BST?
左子树比根节点小,右子树不小于根节点
中序遍历是不降序列的充分非必要条件
Validate Binary Search Tree
https://leetcode.com/problems/validate-binary-search-tree/description/
http://www.lintcode.com/problem/validate-binary-search-tree/
https://www.jiuzhang.com/solutions/?search=Validate%20Binary%20Search%20Tree
https://leetcode.com/problems/validate-binary-search-tree/discuss/32178/Clean-Python-Solution
Initial: dfs(root.left, Long.MIN_VALUE, root.val) dfs(root.right, root.val Long.MAX_VALUE)
Exit: null, out of min and max
通过存一个边界范围来控制
Search in a Binary Search Tree
https://leetcode.com/problems/search-in-a-binary-search-tree/description/
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/148890/Python-3-lines-DFS-solution-w-a-very-simple-approach
3行搞定,思考的逻辑先考虑关系,再考虑终点
Convert Binary Search Tree to Doubly Linkedlist
https://www.jiuzhang.com/solution/convert-binary-search-tree-to-doubly-linked-list/
Initial: ResultType{first, last}, ResultType result; DoublyListNode node; ResultType left, ResultType right
Process: combine and return the first and last nodes of the doubly-list
Exit: if(null) null, result
Flatten Binary Tree to Linked List
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/37154/8-lines-of-python-solution-(reverse-preorder-traversal)
http://www.lintcode.com/problem/flatten-binary-tree-to-linked-list/
https://www.jiuzhang.com/solutions/flatten-binary-tree-to-linked-list/
Initial: TreeNode leftLast, rightLast: last node of the flatten linkedlist
Process: left != null to connect; Then 3 conditions to return right != null; left != null; return null;
Binary Tree Path Sum
https://www.jiuzhang.com/solution/binary-tree-path-sum/
Binary Search Tree Iterator
https://leetcode.com/problems/binary-search-tree-iterator/description/
In-order Successor in Binary Search Tree
https://www.cnblogs.com/grandyang/p/5306162.html
https://www.jiuzhang.com/solutions/inorder-successor-in-binary-search-tree/
Insert Node in a Binary Search Tree
https://leetcode.com/problems/insert-into-a-binary-search-tree/description/
Remove Node in a Binary Search Tree
https://www.cnblogs.com/billzhou0223/p/5090759.html

4 Quick sort and merge sort

Quicksort

Initial: int[] A, int left, int right, int pivot = A[(left + right) /2]
Process: while(left <= right) {if(left<= right && A[left] < pivot) left++;) same at right; if (left<= right) exchange and left++ and right--;

Merge sort: use extra temp

Compare

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,406评论 5 475
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,976评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,302评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,366评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,372评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,457评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,872评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,521评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,717评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,523评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,590评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,299评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,859评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,883评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,127评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,760评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,290评论 2 342

推荐阅读更多精彩内容