1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Binary Tree Inorder Traversal

Posted on 2014-01-19 21:06  1957  阅读(162)  评论(0编辑  收藏  举报

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;
    }
};