zoukankan      html  css  js  c++  java
  • (微软100题)1.把二元查找树转变成排序的双向链表

    #include <iostream>
    using namespace std;
    
    /*
    1.把二元查找树转变成排序的双向链表
    题目:
    输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
    要求不能创建任何新的结点,只调整指针的指向。
    
    10
    /  
    6	14
    / 	  / 
    4  8 12 16
    
    转换成双向链表
    4=6=8=10=12=14=16。
    */
    
    struct Node{
    	int data;
    	Node *left;
    	Node *right;
    	Node(int d = 0, Node *lr = 0, Node *rr = 0):
    	data(d), left(lr), right(rr)
    	{
    	}
    };
    
    Node *create()
    {
    	Node *root;
    	Node *p4 = new Node(4);
    	Node *p8 = new Node(8);
    	Node *p6 = new Node(6, p4, p8);
    
    	Node *p12 = new Node(12);
    	Node *p16 = new Node(16);
    	Node *p14 = new Node(14, p12, p16);
    
    	Node *p10 = new Node(10, p6, p14);
    	root = p10;
    
    	return root;
    }
    
    Node *change(Node *p, bool asRight)
    {
    	if (NULL == p)
    		return NULL;
    	Node *pLeft = change(p->left, false);
    	if (pLeft)
    		pLeft->right = p;
    	p->left = pLeft;
    
    	Node *pRight = change(p->right, true);
    	if (pRight)
    		pRight->left = p;
    	p->right = pRight;
    
    	Node *r = p;
    	if (asRight)
    	{
    		while (r->left)
    			r = r->left;
    	}else
    	{
    		while (r->right)
    			r = r->right;
    	}
    	return r;
    }
    
    void main(){
    	Node *root = create();
    	Node *tail = change(root, false);
    	while (tail)
    	{
    		cout << tail->data << " ";
    		tail = tail->left;
    	}
    	cout << endl;
    
    	root = create();
    	Node *head = change(root, true);
    	while (head)
    	{
    		cout << head->data << " ";
    		head = head->right;
    	}
    	cout << endl;
    	system("pause");
    }
    


     

  • 相关阅读:
    SYBASE 日志空间满了的几种情况
    命令行对jar包的解压和压缩
    SYBASE 常用 sp_configure
    SYBASE 删除数据库
    【转】从RGB色转为灰度色算法
    C# 指针操作图像 细化处理
    C# 指针操作图像 二值化处理
    C# 对象转换为byte[] ,byte[]还原对象
    javascript 简单加解密
    windows 2003 企业版 下载地址+序列号
  • 原文地址:https://www.cnblogs.com/byfei/p/6389848.html
Copyright © 2011-2022 走看看