码迷,mamicode.com
首页 > 其他好文 > 详细

!!!树的中序,前序线索化遍历

时间:2016-06-26 22:29:21      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

=====

笔记另写:

======

code:

class A{
public:
///inorderMorrisTraversal
    void inorderMorrisTraversal(TreeNode *root){
        TreeNode *curr = root;
        TreeNode *prev = nullptr;
        while(curr!=nullptr){
            if(curr->left == nullptr){
                cout<<curr->val<<" ";
                curr = curr->right;
            }else{
                ///search predecessor
                prev = curr->left;
                while(prev->right !=nullptr && prev->right!=curr){
                    prev = prev->right;
                }
                if(prev->right==nullptr){
                    prev->right = curr;
                    curr = curr->left;
                }else{
                    prev->right = nullptr;///recover the tree
                    cout<<curr->val<<" ";
                    curr = curr->right;
                }
            }///if-else
        }///while
    }
};

 

=== 前序线索化

///
    void preMorris(TreeNode* root){
        TreeNode *curr = root;
        TreeNode *prev = nullptr;
        while(curr!=nullptr){
            if(curr->left==nullptr){
                cout<<curr->val<<" ";
                curr = curr->right;
            }else{
                prev = curr->left;
                while(prev->right!=nullptr && prev->right!=curr){
                    prev = prev->right;
                }
                if(prev->right==nullptr){
                    prev->right = curr;
                    cout<<curr->val<<" ";
                    curr = curr->left;
                }else{
                    prev->right = curr;
                    curr = curr->right;
                }
            }
        }///while
    }

 

!!!树的中序,前序线索化遍历

标签:

原文地址:http://www.cnblogs.com/li-daphne/p/5618583.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!