有序数组转成平衡二叉树,平衡二叉树转成双端链表

#include <vector>
#include <iostream>
using namespace std;


//二叉树的树结构
struct TreeNode{
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(char t) :val(t), left(0), right(0){};
};

//有序数组转成平衡二叉树
//也是一个递归的过程,每次都把数组分为两个部分,
//作为左子树和右子树。

TreeNode* sortedArray2BST(vector<int>& nums) {
	return BST(nums, 0, nums.size() - 1);
}

TreeNode* BST(vector<int>& nums, int s, int t){
	if (s > t)  return 0;
	int mid = (s + t) / 2;
	TreeNode* p = new TreeNode(nums[mid]);
	p->left = BST(nums, s, mid - 1);
	p->right = BST(nums, mid + 1, t);
	return p;
}

//平衡二叉树转成双端链表
//递归实现平衡二叉树转成双端链表
//其实就是一个中序遍历,前中后,输出节点换成建立指针的过程
//一个传递引用的哨兵节点指针,或者全局变量也可以。
//这里我新建了一个node,方便递归。
TreeNode* Tree2List(TreeNode* root){
	TreeNode temp(0);
	TreeNode* p = &temp;
	TreeList(root, p);
	temp.right->left = 0;
	return temp.right;
}

void TreeList(TreeNode* root, TreeNode* &p){
	if (root){
		TreeList(root->left, p);
		p->right = root;
		root->left = p;
		p = root;
		TreeList(root->right, p);
	}
}

void Listprint(TreeNode* root){
	while (root->right){
		cout << root->val << " ";
		root = root->right;
	}
	cout << root->val << endl;
	while (root){
		cout << root->val << " ";
		root = root->left;
	}
	cout << endl;
}


int main()
{
	vector<int> nums = { 1, 2, 3, 5, 7, 9, 12, 13, 15, 17, 18, 20, 21, 22, 24, 25 };
	TreeNode* root = sortedArray2BST(nums);
	TreeNode* head = Tree2List(root);
	Listprint(head);
	return 0;
}

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/juzihongle1/article/details/77934888
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞