二叉树的顺序存储实现及遍历

女爷i 2022-06-06 11:42 323阅读 0赞

关于二叉树的实现,常见的大概有三种实现方法:

  • 顺序存储:采用数组来记录二叉树的所有节点
  • 二叉链表存储: 每个节点保留一个left,right域,指向左右孩子
  • 三叉链表存储: 每个节点保留一个left, right, parent域,指向左右孩子和父亲

根据满二叉树的特性,第i层的节点数量为2^(i-1),对于一个深度为n的二叉树,节点数最多为2^n - 1。因此,只需要定义一个长度为2^n-1的数组即可定义出深度为n的二叉树。

注意:对于非完全二叉树,数组中必然会存在空元素的情况,这样情况下空间浪费比较严重。因此仅建议满二叉树使用顺序存储来实现,以便实现紧凑存储和高效访问。

顺序存储的实现

  • 使用一个数组来存储所有节点
  • 按数组下标进行存储,根节点存储在下标0处,其左孩子存储于下标2*0+1,右孩子存储于下标2*0+2 …依次类型。
  • 下标为i的节点,左右孩子存储于下标2*i+1与2*i+2

简易代码:

  1. public class OrderBinaryTree<T> {
  2. // 二叉树所有节点的顺序存储的数组
  3. public Object[] datas;
  4. // 二叉树的规模最大值为2的deep次方-1
  5. public int arraySize;
  6. // 树的深度
  7. public int deep;
  8. // 默认深度
  9. public static int DEFAULT_DEEP = 8;
  10. public OrderBinaryTree() {
  11. this.deep = DEFAULT_DEEP;
  12. this.arraySize = (int) Math.pow(2, deep) - 1;
  13. this.datas = new Object[arraySize];
  14. }
  15. public OrderBinaryTree(int deep) {
  16. this.deep = deep;
  17. this.arraySize = (int) Math.pow(2, deep) - 1;
  18. this.datas = new Object[arraySize];
  19. }
  20. public OrderBinaryTree(int deep, T root) {
  21. this(deep);
  22. this.datas[0] = root;
  23. }
  24. /**
  25. * 为指定的节点添加子节点
  26. *
  27. * @param index
  28. * 该节点的索引
  29. * @param data
  30. * 被添加为子节点的索引
  31. * @param left
  32. * 是否为左孩子
  33. * @throws Exception
  34. **/
  35. public void add(int index, T data, Boolean left) throws Exception {
  36. int needSize = left? 2 * index + 1: 2 * index + 2;
  37. if (needSize >= datas.length) {
  38. throw new Exception("数组越界");
  39. }
  40. if (left) {
  41. datas[2 * index + 1] = data;
  42. } else {
  43. datas[2 * index + 2] = data;
  44. }
  45. }
  46. /**
  47. * 为指定的节点添加子节点
  48. *
  49. * @param index
  50. * 该节点的索引
  51. * @return 子节点的索引
  52. **/
  53. public int getLeft(int index) throws Exception {
  54. if (index >= 0 && datas.length > 2 * index + 1) {
  55. return 2 * index + 1;
  56. }
  57. return -1;
  58. }
  59. /**
  60. * 为指定的节点添加子节点
  61. *
  62. * @param index
  63. * 该节点的索引
  64. * @return 子节点的索引
  65. **/
  66. public int getRight(int index) throws Exception {
  67. if (index >= 0 && datas.length > 2 * index + 2) {
  68. return 2 * index + 2;
  69. }
  70. return -1;
  71. }
  72. }

上述代码实现了一个非常简易的二叉树,当然二叉树还有很多操作上述没有列出来。现在使用上述定义的数据结构来实现一个二叉树实例:

  1. OrderBinaryTree<String> orderBinaryTree = new OrderBinaryTree<String>(3, "a");
  2. orderBinaryTree.add(0, "b", true);
  3. orderBinaryTree.add(0, "c", false);
  4. orderBinaryTree.add(1, "d", true);
  5. orderBinaryTree.add(1, "e", false);
  6. orderBinaryTree.add(2, "f", true);
  7. orderBinaryTree.add(2, "g", false);

上述定义来一个如下面所示的满二叉树:

二叉树遍历

遍历二叉树指的是按某种规律依次访问二叉树的每个节点,对于二叉树的遍历就是将一个非线性结构的二叉树中节点排列在一个线性序列上的过程。

遍历方法:

  • 深度优先遍历
  • 广度优先遍历

其中广度优先遍历非常简单,就按层遍历,访问第一层,第二层,..对于我们的顺序实现的二叉树来说,底层数组就是其广度优先遍历的结果。现在我们重点介绍深度优先遍历。

深度优先遍历

深度优先遍历分3种(假设L,D,R分别表示左,根,右子树):

  • 先序遍历: DLR
  • 中序遍历: LDR
  • 后序遍历: LRD

一·先序遍历
对于先序遍历,或许你经常会看到如下的递归代码:

  1. public void travPreRecursion() {
  2. return this.preRecursion(0);
  3. }
  4. private List preRecursion(int index) {
  5. List list = new ArrayList();
  6. list.add(datas[index]);
  7. if (2 * index + 1 < arraySize) {
  8. list.addAll(preRecursion(2 * index + 1));// 左儿子
  9. }
  10. if (2 * index + 2 < arraySize) {
  11. list.addAll(preRecursion(2 * index + 2));// 右儿子
  12. }
  13. return list;
  14. }

笔者认为递归算法不仅效率低而且不利于阅读者理解,因此笔者将其修改为循环版

先沿着最左侧通路自顶而下访问沿路节点,再底而上依次遍历这些节点的右节点

  1. public List travPreCirculate() {
  2. int index = 0;
  3. //定义一个辅助栈来完成最左侧通路自顶而下的节点的右节点
  4. Stack<Integer> stack = new Stack<Integer>();
  5. List list = new ArrayList();
  6. try {
  7. while (true) {
  8. //从index开始最左侧通路自顶而下的访问节点,直到底
  9. //并把每个访问到的节点存储在stack
  10. setRightStack(index, stack, list);
  11. //如果一条左子数链路中没有任何一个右子数,则遍历结束
  12. if (stack.empty()) {
  13. break;
  14. }
  15. // 从来临时栈中依次pop出节点,并继续取其右节点
  16. index = stack.pop();
  17. }
  18. } catch (Exception e) {
  19. // TODO Auto-generated catch block
  20. e.printStackTrace();
  21. }
  22. return list;
  23. }
  24. public void setRightStack(int index, Stack<Integer> stack, List list) {
  25. try {
  26. // 从index开始访问其左子数,并将其所有的右子树全部push到临时栈中
  27. while (index >= 0) {
  28. list.add(datas[index]);
  29. int right = getRight(index);
  30. if (right > 0) {
  31. stack.push(right);
  32. }
  33. index = this.getLeft(index);
  34. }
  35. } catch (Exception e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. }
  39. }

二·中序遍历

对于中序遍历,与先序遍历类似,你经常会看到如下的递归代码:

  1. public void travPreRecursion() {
  2. return this.preRecursion(0);
  3. }
  4. private List preRecursion(int index) {
  5. List list = new ArrayList();
  6. if (2 * index + 1 < arraySize) {
  7. list.addAll(preRecursion(2 * index + 1));// 左儿子
  8. }
  9. list.add(datas[index]);
  10. if (2 * index + 2 < arraySize) {
  11. list.addAll(preRecursion(2 * index + 2));// 右儿子
  12. }
  13. return list;
  14. }

当然,笔者还是要将其修改为循环模式

沿着最左侧链路,自底而上依次访问每个节点的右子树

  1. public void travInCirculate() {
  2. int index = 0;
  3. Stack<Integer> stack = new Stack<Integer>();
  4. List list = new ArrayList();
  5. while (true) {
  6. //将index节点的左子树全部push到stack中
  7. setLeftStack(index, stack);
  8. if (stack.isEmpty()) {
  9. break;
  10. }
  11. //pop出左子树
  12. index = stack.pop();
  13. list.add(datas[index]);
  14. try {
  15. //取该节点的右孩子,并继续push其所有左子树到栈中
  16. index = this.getRight(index);
  17. } catch (Exception e) { // TODO Auto-generated catch
  18. block e.printStackTrace();
  19. }
  20. }
  21. }
  22. public void setLeftStack(int index, Stack<Integer> stack) {
  23. try {
  24. // 将root开始的所有右子树全部push到临时栈中
  25. while (index >= 0) {
  26. stack.push(index);
  27. index = getLeft(index);
  28. }
  29. } catch (Exception e) {
  30. // TODO Auto-generated catch block
  31. e.printStackTrace();
  32. }
  33. }

三.后序遍历

后序遍历的递归代码:

  1. // 后序遍历(递归)
  2. public void travPostRecursion() {
  3. postRecursion(0);
  4. }
  5. public void postRecursion(int index) {
  6. if (2 * index + 1 < arraySize) {
  7. postRecursion(2 * index + 1);// 左儿子
  8. }
  9. if (2 * index + 2 < arraySize) {
  10. postRecursion(2 * index + 2);// 右儿子
  11. }
  12. System.out.println(datas[index]);
  13. }

与上述一致,改造为循环

先序,中序遍历中,第一位元素一定是某个节点的左孩子。
当后序遍历不一定,后序遍历的首位原型应该是左子树中度最高的一个元素,可能是左孩子也有可能是右孩子

  1. // 后序遍历(循环)
  2. public void travPostCirculate() {
  3. int index = 0;
  4. Stack<Integer> stack = new Stack<Integer>();
  5. List list = new ArrayList();
  6. while (true) {
  7. //从index开始将其左孩子push到栈中
  8. //如果到了最后一个左孩子,该节点存在右孩子,则继续push
  9. setStackForPost(index, stack);
  10. if (stack.empty()) {
  11. break;
  12. }
  13. index = stack.pop();
  14. list.add(datas[index]);
  15. // 获取其右兄弟
  16. int parent;
  17. try {
  18. parent = this.parent(index);
  19. int right = this.getRight(parent);
  20. index = index == right ? -1 : right;
  21. } catch (Exception e) {
  22. // TODO Auto-generated catch block
  23. e.printStackTrace();
  24. }
  25. }
  26. }
  27. public void setStackForPost(int index, Stack stack) {
  28. try {
  29. // 将root开始的所有右子树全部push到临时栈中
  30. while (index >= 0) {
  31. stack.push(index);
  32. int pre = index;
  33. index = getLeft(index);
  34. if (index < 0) {
  35. // 当到达最左子树时,如果该最左子树存在右子树,则遍历从该右子树开始
  36. index = this.getRight(pre);
  37. }
  38. }
  39. } catch (Exception e) {
  40. // TODO Auto-generated catch block
  41. e.printStackTrace();
  42. }
  43. }

补充

对于中序编译,也会看到如下写法,思路是一样

  1. // 中序遍历(循环)
  2. public void travInCirculate() {
  3. int index = 0;
  4. Stack<Integer> stack = new Stack<Integer>();
  5. try {
  6. while (true) {
  7. if(index>=0) {
  8. stack.push(index);
  9. index = this.getLeft(index);
  10. }else if(!stack.empty()) {
  11. index = stack.pop();
  12. System.out.println(datas[index]);
  13. index = this.getRight(index);
  14. }else {
  15. break;
  16. }
  17. }
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. }
  21. }

笔者认为中序遍历是最重要的,一项最基本的操作将是定位中序遍历中某个节点的直接后继节点,在平衡二叉树的等场景中会使用

发表评论

表情:
评论列表 (有 0 条评论,323人围观)

还没有评论,来说两句吧...

相关阅读

    相关 存储

    一、二叉树的存储结构 1. 顺序存储 用一组连续的存储单元依次自上而下、自左至右存储完全二叉树上的结点元素。 > 注意,存放的是是完全二叉树的结点元素。 例如: