Binary Tree Traversal in O(1) space and O(n) time

Description:

Achieve binary tree tranversal in O(1) space and O(n) time.

解题方法:

Morris Traversal:
1
2

For the current node:

  1. If it doesn’t have left child, print out and go to the right child.
  2. Ohterwise, find out the most right leaf in its left child tree. Then, if this mostRightLeaf->right == curr node, print out and go to the right child; Or, make mostRightLeaf->right = curr, then go to the left child.
  3. Repeat step 1 and 2, untill curr == NULL;

Time Complexity:

time: O(n)
space: O(1)

完整代码:

Inorder:
vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        if(!root)
            return result;
        TreeNode* curr = root;
        while(curr) {
            TreeNode* mostRight = NULL;
            if(curr->left) {
                mostRight = findMostRight(curr, curr->left);
            }
            if(!mostRight || (mostRight && mostRight->right == curr)) {
                cout<<curr->val<<endl;
                result.push_back(curr->val);
                curr = curr->right;
            } else {
                mostRight->right = curr;
                curr = curr->left;
            }
        }
        return result;
    }
    
    TreeNode* findMostRight(TreeNode* prev, TreeNode* root) {
        if(!root)
            return NULL;
        while(root->right && root->right != prev) {
            root = root->right;
        }
        return root;
    }
    原文作者:黑山老水
    原文地址: https://www.jianshu.com/p/27d213d5f8f2
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞