The general idea:
In fact, this binary tree problem mostly with "recursion" to solve. This question is just the beginning I did not find the idea of recursion.
If there are multiple nodes in the sub-tree , you need to find clear in the end what is the root node before and after the . Such as:
May know, this is obviously in accordance with the order tree traversal thing. .
then. . . Analysis for a long time. . . Because preorder binary sort tree originally ordered, so in fact, preorder, just to consider a pre nodes to link the context of it ! !
This code also I studied for a while, pay attention to pre pointer is a reference variable. Code structure is in order traversal of the structure, just to figure out what I currently do, pre pointer should change how.
AC Code:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree)
{
//先判空和一个
if(pRootOfTree==NULL)
{
return NULL;
}
if(pRootOfTree->left==NULL && pRootOfTree->right==NULL)
return pRootOfTree;
TreeNode* pre = NULL;
convert_recursive(pRootOfTree,pre); //初始的pre值是null
TreeNode* p = pRootOfTree;
while(p->left)
p=p->left;
return p; //结果链表的头结点是树的最左下方的结点
}
void convert_recursive(TreeNode* t, TreeNode* &pre) //注意pre要加引用
{
if(t==NULL)
return;
convert_recursive(t->left,pre);
//仿照中序遍历,这里是主要的操作:
t->left=pre; //注意,这里要理解到!!!要等左子树以同样逻辑得到的pre作为本根节点的在链表中的上一个元素
if(pre) pre->right = t; //注意是双向链表!
pre = t; //这步也很关键
convert_recursive(t->right,pre);
}
};