BST Traversal
Prompt
Write three functions that take in a Binary Search Tree (BST) and an empty array, traverse the BST, add its nodes’ values to the input array, and return that array. The three functions should traverse the BST using the
in-order, pre-order, and post-order treetraversal techniques, respectively. If you’re unfamiliar with tree-traversal
techniques, we recommend watching the Conceptual Overview section of this question’s video explanation before starting to code.
Each BST node has an integer value , a left child node, and a right child node. A node is said to be a valid BST node if and only if it satises the BST property: its value is strictly greater than the values of every node to its left; its value is less than or equal to the values of every node to its right; and its children nodes are either valid
BST nodes themselves or None / null .
Sample Input
Sample Output
inOrderTraverse: [1, 2, 5, 5, 10, 15, 22]
preOrderTraverse: [10, 5, 2, 1, 5, 15, 22]
postOrderTraverse: [1, 2, 5, 5, 22, 15, 10]
Solution
import java.util.List;
class Program {
public static List<Integer> inOrderTraverse(BST tree, List<Integer> array) {
// O(n) time | O(h)
if (tree.left != null) {
inOrderTraverse(tree.left, array);
}
array.add(tree.value);
if (tree.right != null) {
inOrderTraverse(tree.right, array);
}
return array;
}
public static List<Integer> preOrderTraverse(BST tree, List<Integer> array) {
array.add(tree.value);
if (tree.left != null) {
preOrderTraverse(tree.left, array);
}
if (tree.right != null) {
preOrderTraverse(tree.right, array);
}
return array;
}
public static List<Integer> postOrderTraverse(BST tree, List<Integer> array) {
if (tree.left != null) {
postOrderTraverse(tree.left, array);
}
if (tree.right != null) {
postOrderTraverse(tree.right, array);
}
array.add(tree.value);
return array;
}
static class BST {
public int value;
public BST left;
public BST right;
public BST(int value) {
this.value = value;
}
}
}
How to Bug Free
谨慎输出条件
- 层次遍历
推荐阅读
-
C语言实现BST二叉排序树的基本操作
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
LeetCode --- 783. Minimum Distance Between BST Nodes 解题分析
-
STL源码笔记(17)—二叉排序树BST(C++封装)
-
C语言实现二叉查找树(BST)的基本操作
-
js Element Traversal规范中的元素遍历方法
-
LeetCode 426. 将二叉搜索树转化为排序的双向链表(BST中序循环遍历)
-
二叉搜索树(二叉排序树)BST与双向列表的转换
-
POJ 2309 BST G++
-
PAT甲级1143 Lowest Common Ancestor BST+LCA