/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* midSort(struct TreeNode* root, int* count, struct TreeNode** tail, struct TreeNode** head)
{
if(NULL == root) return;
midSort(root->left, count, tail, head);
struct TreeNode *newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
if(NULL == newNode) return;
newNode->val = root->val;
newNode->left = NULL;
newNode->right = NULL;
if(NULL == *tail)
{
*head = *tail = newNode;
}
else
{
(*tail)->right = newNode;
(*tail) = (*tail)->right;
}
(*count) += 1;
if(*count > 100) return;
midSort(root->right, count, tail, head);
}
struct TreeNode* increasingBST(struct TreeNode* root){
if(NULL == root) return NULL;
if(NULL == root->left && NULL == root->right) return root;
int count = 0;
struct TreeNode *res = NULL;
struct TreeNode *head = NULL;
midSort(root, &count, &res, &head);
return head;
}
给定一个树,按中序遍历重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
示例 :
输入:[5,3,6,2,4,null,8,1,null,null,null,7,9]
输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
提示:
给定树中的结点数介于 1 和 100 之间。
每个结点都有一个从 0 到 1000 范围内的唯一整数值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/increasing-order-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**中序遍历(LDR)**是二叉树遍历的一种,也叫做中根遍历、中序周游。在二叉树中,中序遍历首先遍历左子树,然后访问根结点,最后遍历右子树。
附:对给定的整数序列,建立一棵二叉排序树,并按中序遍历输出树中节点:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *lchild,*rchild;
}BSTNode;
BSTNode *insert(BSTNode *t,BSTNode *s)
{
BSTNode *p,*q; //p指向欲插入的节点,q指向p节点的父节点
if(t==NULL) return s;
p=t; //p指向根节点
while(p) //使q成为s的父节点,p指向s的位置
{
q=p;
if(s->data==p->data)
{
return t;
}
if(s->data >p->data)
{
p=p->rchild;
}
else
p=p->lchild;
}
if(s->data >q->data)
{
q->rchild=s;
}
else
q->lchild=s;
return t;
}
BSTNode *create()
{
BSTNode *t,*s;
int e;
t=NULL;
scanf("%d",&e);
while(e!=-1)
{
BSTNode *s=(BSTNode *)malloc(sizeof(BSTNode));
s->lchild =NULL;
s->rchild =NULL;
s->data =e;
t=insert(t,s);
scanf("%d",&e);
}
return t;
}
void InOrder(BSTNode *t)
{
if(t)
{
InOrder(t->lchild );
printf("%d,",t->data );
InOrder(t->rchild );
}
}