Alg.25 BST Traversal

From algoexpert.io

This one will uses 3 ways to traverse a BST (in-order/pre-order/post-order), the code implementation is pretty straightforward:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

public static List<Integer> inOrderTraverse(BST tree, List<Integer> array) {
BST current = tree;
if (current != null) {
inOrderTraverse(current.left, array);
array.add(current.value);
inOrderTraverse(current.right, array);
}
return array;
}

public static List<Integer> preOrderTraverse(BST tree, List<Integer> array) {
BST current = tree;
if (current != null) {
array.add(current.value);
preOrderTraverse(current.left, array);
preOrderTraverse(current.right, array);
}
return array;
}

public static List<Integer> postOrderTraverse(BST tree, List<Integer> array) {
BST current = tree;
if (current != null) {
postOrderTraverse(current.left, array);
postOrderTraverse(current.right, array);
array.add(current.value);
}
return array;
}

Time complexity: O(n); Space complexity: O(n).

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2021 Zirun Lin

Thanks~

支付宝
微信