File tree Expand file tree Collapse file tree 2 files changed +39
-1
lines changed
Expand file tree Collapse file tree 2 files changed +39
-1
lines changed Original file line number Diff line number Diff line change @@ -273,7 +273,7 @@ leetcode 题解,记录自己的 leetcode 解题之路。
273273
274274- [ 数据结构] ( ./thinkings/basic-data-structure.md )
275275- [ 基础算法] ( ./thinkings/basic-algorithm.md )
276- - [ 二叉树的遍历] ( ./thinkings/binary-tree-traversal.md )
276+ - [ 二叉树的遍历] ( ./thinkings/binary-tree-traversal.md ) 🖊
277277- [ 动态规划] ( ./thinkings/dynamic-programming.md )
278278- [ 哈夫曼编码和游程编码] ( ./thinkings/run-length-encode-and-huffman-encode.md )
279279- [ 布隆过滤器] ( ./thinkings/bloom-filter.md )
Original file line number Diff line number Diff line change @@ -100,3 +100,41 @@ BFS 的关键点在于如何记录每一层次是否遍历完成, 我们可以
1001004 . 如果不为 null,说明这一层还没完,则将其左右子树依次入队列。
101101
102102相关问题[ 102.binary-tree-level-order-traversal] ( ../problems/102.binary-tree-level-order-traversal.md )
103+
104+ ## 双色标记法
105+
106+ 我们直到垃圾回收算法中,有一种算法叫三色标记法。 即:
107+
108+ - 用白色表示尚未访问
109+ - 灰色表示尚未完全访问子节点
110+ - 黑色表示子节点全部访问
111+
112+ 那么我们可以模仿其思想,使用双色标记法来统一三种遍历。
113+
114+ 其核心思想如下:
115+
116+ - 使用颜色标记节点的状态,新节点为白色,已访问的节点为灰色。
117+ - 如果遇到的节点为白色,则将其标记为灰色,然后将其右子节点、自身、左子节点依次入栈。
118+ - 如果遇到的节点为灰色,则将节点的值输出。
119+
120+ 使用这种方法实现的中序遍历如下:
121+
122+ ``` python
123+ class Solution :
124+ def inorderTraversal (self , root : TreeNode) -> List[int ]:
125+ WHITE , GRAY = 0 , 1
126+ res = []
127+ stack = [(WHITE , root)]
128+ while stack:
129+ color, node = stack.pop()
130+ if node is None : continue
131+ if color == WHITE :
132+ stack.append((WHITE , node.right))
133+ stack.append((GRAY , node))
134+ stack.append((WHITE , node.left))
135+ else :
136+ res.append(node.val)
137+ return res
138+ ```
139+
140+ 如要实现前序、后序遍历,只需要调整左右子节点的入栈顺序即可。
You can’t perform that action at this time.
0 commit comments