Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //inorder traversal can b solved in 3 ways
- /*
- 1.Iterative solution using stack: O(n) time and O(n) space;
- 2.Recursive solution: O(n) time and O(n) space (function call stack);
- 3.Morris traversal: O(n) time and O(1) space.
- */
- /*morris traversal
- 1...If left child is null, print the current node data. Move to right child.
- ….Else, Make the right child of the inorder predecessor point to the current node. Two cases arise:
- ………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.
- ………b) The right child is NULL. Set it to current node. Print current node’s data and move to left child of current node.
- 2...Iterate until current node is not NULL.
- */
- class Solution {
- public:
- vector<int> inorderTraversal(TreeNode* root) {
- vector<int> nodes;
- while (root) {
- if (root -> left) {
- TreeNode* pre = root -> left;
- while (pre -> right && pre -> right != root) {
- pre = pre -> right;
- }
- if (!pre -> right) {
- pre -> right = root;
- root = root -> left;
- } else {
- pre -> right = NULL;
- nodes.push_back(root -> val);
- root = root -> right;
- }
- } else {
- nodes.push_back(root -> val);
- root = root -> right;
- }
- }
- return nodes;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement