info

《数据结构与算法》清华-邓俊辉
https://www.bilibili.com/video/BV1ub411H7PK?p=5

二叉树

二叉树遍历

前序遍历

image.png

  1. // 递归版本
  2. void traverse(node){
  3. while (node){
  4. visit(node);
  5. traverse(node->left);
  6. traverse(node->right);
  7. }
  8. }
  9. void visitLeftBranch(node, stack){
  10. while (node){
  11. visit(node);
  12. stack.push(node->right);
  13. node = node -> left;
  14. }
  15. }
  16. void pre_traverse(node){
  17. while (true){
  18. visitLeftBranch(node, stack);
  19. if (stack.empty()) break;
  20. node = stack.pop();
  21. }
  22. }

中序遍历

截屏2021-03-19 21.46.29.png

  1. void goLeftBranch(node, stack){
  2. while (node) {
  3. stack.push(node);
  4. node = node->left;
  5. }
  6. }
  7. void inorder_traverse(node){
  8. while (true){
  9. goLeftBranch(node, stack);
  10. if (stack.empty()) break;
  11. node = stack.pop();
  12. visit(node);
  13. stack = stack->right;
  14. }
  15. }