Advertisement
RaFiN_

inorder traversal

Dec 20th, 2019
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1.  
  2.  
  3.  
  4. //inorder traversal can b solved in 3 ways
  5.  
  6.  
  7. /*
  8. 1.Iterative solution using stack: O(n) time and O(n) space;
  9. 2.Recursive solution: O(n) time and O(n) space (function call stack);
  10. 3.Morris traversal: O(n) time and O(1) space.
  11.  
  12. */
  13.  
  14. /*morris traversal
  15. 1...If left child is null, print the current node data. Move to right child.
  16. ….Else, Make the right child of the inorder predecessor point to the current node. Two cases arise:
  17. ………a) The right child of the inorder predecessor already points to the current node. Set right child to NULL. Move to right child of current node.
  18. ………b) The right child is NULL. Set it to current node. Print current node’s data and move to left child of current node.
  19. 2...Iterate until current node is not NULL.
  20. */
  21.  
  22. class Solution {
  23. public:
  24.     vector<int> inorderTraversal(TreeNode* root) {
  25.         vector<int> nodes;
  26.         while (root) {
  27.             if (root -> left) {
  28.                 TreeNode* pre = root -> left;
  29.                 while (pre -> right && pre -> right != root) {
  30.                     pre = pre -> right;
  31.                 }
  32.                 if (!pre -> right) {
  33.                     pre -> right = root;
  34.                     root = root -> left;
  35.                 } else {
  36.                     pre -> right = NULL;
  37.                     nodes.push_back(root -> val);
  38.                     root = root -> right;
  39.                 }
  40.             } else {
  41.                 nodes.push_back(root -> val);
  42.                 root = root -> right;
  43.             }
  44.         }
  45.         return nodes;
  46.     }
  47. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement