zoukankan      html  css  js  c++  java
  • Cracking-- 17.13 将二叉树转换成双向链表

    在书的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;
    }
  • 相关阅读:
    poj_1836 动态规划
    动态规划——最长上升子序列
    poj_3260 动态规划
    poj_3628 动态规划
    动态规划——背包问题
    poj_2559 单调栈
    poj_3415 后缀数组+单调栈
    poj_2823 线段树
    poj_2823 单调队列
    poj_3250 单调栈
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3954419.html
Copyright © 2011-2022 走看看