Day38: [LeetCode中等] 114. 二叉树展开为链表
题源:
来自leetcode题库:
https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/
代码:
dirty code凑合看吧
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* res;
pair<TreeNode*,TreeNode*> f(TreeNode* root){
if(!(root->left==NULL&&root->right==NULL)){
if(root->left!=NULL&&root->right!=NULL){
pair<TreeNode*,TreeNode*> temp1=f(root->left),temp2=f(root->right);
root->right=temp1.first;
root->left=NULL;
temp1.second->right=temp2.first;
temp1.second->left=NULL;
return make_pair(root,temp2.second);
}else if(root->left==NULL){
pair<TreeNode*,TreeNode*> temp1=f(root->right);
root->right=temp1.first;
root->left=NULL;
return make_pair(root,temp1.second);
}else{
pair<TreeNode*,TreeNode*> temp1=f(root->left);
root->right=temp1.first;
root->left=NULL;
return make_pair(root,temp1.second);
}
}else return pair<TreeNode*,TreeNode*>(root,root);;
}
void flatten(TreeNode* root) {
if(!root) return;
f(root);
}
};