Home > Back-end >  Looking for a great god help Chou Chou which piece of logic
Looking for a great god help Chou Chou which piece of logic

Time:11-25

Force on a topic (give you a tree, please according to the sequence traversal rearrange tree, the leftmost node in the tree now is the root of the tree, and each node is not left child node, there is only one right child node,),
With preorder traversal first I get the number of nodes, and then use the sequence traversal save node values in an array, and then from the array into a target tree,
Submitted by example, can be in the default time met only a node of the input error, output the ten nodes, nine is - 1094795586, before the last one is to value, I ran it again on VS is right, hope leaders help and see what went wrong, it is
The code is as follows:
 int temp=0, count=0; 
/* binary tree before sequence traversal */
Void PreOrderTraverse (TreeNode * T) {
If (T==NULL)
return;
count++;
PreOrderTraverse (T - & gt; Left);
PreOrderTraverse (T - & gt; Right);
}
/* binary tree of sequence traversal */

The Status InOrderTraverse (TreeNode * T, int * nums) {
If (T==NULL)
return FALSE;
InOrderTraverse (T - & gt; Left, nums);
Nums=[temp++] T - & gt; Val.
InOrderTraverse (T - & gt; Right, nums);
return TRUE;
}

Struct TreeNode * increasingBST (struct root TreeNode *) {
PreOrderTraverse (root);
Int * nums=(int *) malloc (sizeof (int) * count);
InOrderTraverse (root, nums);
TreeNode * T=(TreeNode *) malloc (sizeof (TreeNode));
TreeNode * temp=T;
for (int i=0; I & lt; The count. I++) {
TreeNode * p=(TreeNode *) malloc (sizeof (TreeNode));
P - & gt; Val=nums [I];
P - & gt; Left=p - & gt; Right=NULL;
Temp - & gt; Right=p;
Temp=temp - & gt; Right;
}
Return T - & gt; Right;
}
  • Related