Algorithm | Tree traversal

柔光的暖阳◎ 2022-01-06 16:33 320阅读 0赞

There are three types of depth-first traversal: pre-order,in-order, and post-order.

For a binary tree, they are defined as operations recursively at each node, starting with the root node as follows:

Pre-order

Visit the root.
Traverse the left subtree.
Traverse the right subtree.

  1. iterativePreorder(node)
  2. parentStack = empty stack
  3. parentStack.push(null)
  4. top = node
  5. while ( top != null )
  6. visit( top )
  7. if ( top.right != null )
  8. parentStack.push(top.right)
  9. if ( top.left != null )
  10. parentStack.push(top.left)
  11. top = parentStack.pop()

In-order

Traverse the left subtree.
Visit root.
Traverse the right subtree.

  1. iterativeInorder(node)
  2. parentStack = empty stack
  3. while (not parentStack.isEmpty() or node null)
  4. if (node null)
  5. parentStack.push(node)
  6. node = node.left
  7. else
  8. node = parentStack.pop()
  9. visit(node)
  10. node = node.right

Post-order

Traverse the left subtree.
Traverse the right subtree.
Visit the root.

  1. iterativePostorder(node)
  2. parentStack = empty stack
  3. lastnodevisited = null
  4. while (not parentStack.isEmpty() or node null)
  5. if (node null)
  6. parentStack.push(node)
  7. node = node.left
  8. else
  9. peeknode = parentStack.peek()
  10. if (peeknode.right null and lastnodevisited peeknode.right)
  11. /* if right child exists AND traversing node from left child, move right */
  12. node = peeknode.right
  13. else
  14. parentStack.pop()
  15. visit(peeknode)
  16. lastnodevisited = peeknode

Morris Travel

  1. 1 /**
  2. 2 * Definition for binary tree
  3. 3 * struct TreeNode {
  4. 4 * int val;
  5. 5 * TreeNode *left;
  6. 6 * TreeNode *right;
  7. 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. 8 * };
  9. 9 */
  10. 10 class Solution {
  11. 11 public:
  12. 12 vector<int> inorderTraversal(TreeNode *root) {
  13. 13 vector<int> ret;
  14. 14 if (!root) return ret;
  15. 15 TreeNode *cur = root;
  16. 16
  17. 17 while (cur) {
  18. 18 if (!cur->left) {
  19. 19 ret.push_back(cur->val);
  20. 20 cur = cur->right;
  21. 21 } else {
  22. 22 TreeNode *rightmost = cur->left;
  23. 23 while (rightmost->right != NULL && rightmost->right != cur) rightmost = rightmost->right;
  24. 24 if (rightmost->right == cur) {
  25. 25 rightmost->right = NULL;
  26. 26 ret.push_back(cur->val);
  27. 27 cur = cur->right;
  28. 28 } else {
  29. 29 rightmost->right = cur;
  30. 30 cur = cur->left;
  31. 31 }
  32. 32 }
  33. 33 }
  34. 34
  35. 35 return ret;
  36. 36 }
  37. 37 };

后序:

161440377403840.jpg

转载于:https://www.cnblogs.com/linyx/p/3627184.html

发表评论

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

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

相关阅读

    相关 A1020. Tree Traversals(25)

    这是一题二叉树遍历的典型题,告诉我们中序遍历和另外一种遍历序列,然后求任何一种遍历序列。 这题的核心: 1. 建树 2. BFS include<bits/