Tree traversals树的遍历和LeetCode99修复二进制搜索树
树的遍历
- 树(tree)作为一种非线性数据结构,可以以不同的方式对其进行遍历(traverse),如前序(preorder),中序(inorder)和后序(postorder)。
- 数组(Array),链表(Linked List),队列(Queues),和栈(Stack)这些线性数据结构只能使用单一的逻辑结构来遍历他们。这展现Tree这种数据结构的优势。
树知识点
这篇文章主要包括
- **深度优先遍历(Depth First Searching)**方式及其应用
- 广度优先遍历(Breadth First or Level Order Searching)
- 时空复杂度分析(Time and Auxiliary Space Complexity)
- LeetCode99题,修复BST二进制搜索树,算法+伪代码+Code。
DFS和BFS例子
深度优先结果
- 前序遍历(根–>左–>右):1 2 4 5 3;
- 中序遍历(左–>根–>右):4 2 5 1 3;
- 后序遍历(左–>右–>根):4 5 2 3 1;
广度优先结果
1 2 3 4 5
来一个更难的例子练练手
中前后序算法+应用场景
- Inorder Traversal:
Algorithm Inorder(tree)
- Traverse the left subtree, i.e., call Inorder(left-subtree)
- Visit the root.
- Traverse the right subtree, i.e., call Inorder(right-subtree)
Application: 二进制搜索树(Binary Search tree)的排序和倒序
BST中,左节点.value<root.value<右节点.value,对于所有子树都必须满足。中序遍历的结果恰好是从小到大非递减的树的节点值的表示。
如果想要得到一颗非递增的二进制搜索树,可以使用中序遍历的变体,其中将中序遍历结果颠倒即可。
- Preorder Traversal:
Algorithm Inorder(tree)
- Visit the root.</