代码:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode* getRight(TreeNode *root){ //找到最右边的结点
if(!root) return nullptr;
TreeNode *p = root;
while(p->right) p = p->right;
return p;
}
TreeNode* Convert(TreeNode* pRootOfTree) {
if(!pRootOfTree) return nullptr;
TreeNode *p = getRight(pRootOfTree->left); //首先找到左子树的最右边的节点
TreeNode *head = Convert(pRootOfTree->left); //然后将左子树处理成链表
if(p){ //将左子树与根结点连接
p->right = pRootOfTree;
pRootOfTree->left = p;
}else pRootOfTree->left = nullptr;
TreeNode *q = Convert(pRootOfTree->right); //将右子树处理成链表
if(q){ //将右子树与根结点连接
q->left = pRootOfTree;
pRootOfTree->right = q;
}else pRootOfTree->right = nullptr;
return head == nullptr ? pRootOfTree : head;
}
};