qingcheng奕  

在书的105页

使用中根遍历的思想

left 之后 为 root 之后 为 right

则对左子树来说

left->right = root; root->left = left;

对右子树来说

root->right = right-> -> -> left;

left->left 为根的根   的根

而right->left 则为直接的根

 

#include <iostream>
#include <vector>

using namespace std;
 
struct node {
    int val;
    node *left;
    node *right;
    node(int _val){
        val = _val;
        left = NULL;
        right = NULL;
    }
};

node* change(node *root)
{
    if(root == NULL)
        return NULL;

    node *retNode = NULL;
    if(root->left == NULL && root->right == NULL)
    {
        return root;
    }
    
    if(root->left)
    {
        retNode = change(root->left );
        retNode->right = root;
        root->left = retNode;
        retNode = root;
    }

    if(root->right)
    {
        retNode = change(root->right);
            
        node* tmp = retNode;
        while(tmp->left)
            tmp = tmp->left;
        root->right = tmp;

        tmp->left = root;    
    }
    
    return retNode;
}
int main()
{
    node *n1 = new node(12);
    node *n2 = new node(8);
    node *n3 = new node(15);
    node *n4 = new node(6);
    node *n5 = new node(10);
    node *n6 = new node(13);
    node *n7 = new node(20);
    n1->left = n2;
    n1->right = n3;

    n2->left = n4;
    n2->right = n5;
    n3->left = n6;
    n3->right = n7;

    node *ans;
    ans = change(n1);
    return 0;
}

 

posted on 2014-09-03 19:36  qingcheng奕  阅读(210)  评论(0编辑  收藏  举报