[leetcode]Binary Tree Inorder Traversal

Morris遍历

 

就是利用节点的right指针

 

当前节点为curr

1. left为空,说明curr是子节点,所以输出,并且curr = curr->right

2. left不为空,tmp=curr->left 然后一直找tmp的右子树,知道tmp->right为空或者等于curr

    如果为空,说明还木有处理过,tmp->right = curr,然后curr = curr -> left

    不为空,说明前面已经处理过鸟,输出这个节点,然后设为空, curr = curr -> right(因为left遍历完了

 

http://www.cnblogs.com/AnnieKim/archive/2013/06/15/morristraversal.html

 

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode *root) {
        TreeNode* curr = root;
        vector<int> ans;
        if(root == nullptr) return ans;
        while(curr) {
            if(curr->left == nullptr) {
                ans.push_back(curr->val);
                curr = curr->right;
            } else {
                TreeNode* prev = curr->left;
                while(prev->right && prev->right!=curr) prev = prev->right;
                if(prev->right == nullptr) {
                    prev->right = curr;
                    curr = curr->left;
                } else {
                    ans.push_back(curr->val);
                    curr = curr->right;
                    prev->right = nullptr;
                }
            }
        }
        return ans;
    }
};

 

你可能感兴趣的:(LeetCode)