解法一:
//时间复杂度O(n), 空间复杂度O(n)
/**
* 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:
void flatten(TreeNode* root, TreeNode* r_chd) {
if(!root->left && !root->right) {
root->right = r_chd;
return;
}
if(root->right) flatten(root->right, r_chd);
else root->right = r_chd;
if(root->left) {
flatten(root->left, root->right);
root->right = root->left;
root->left = nullptr;
}
}
void flatten(TreeNode* root) {
if(!root) return;
flatten(root, nullptr);
}
};
解法二:
//时间复杂度O(n), 空间复杂度O(n)
/**
* 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:
void flatten(TreeNode* root) {
if(!root) return;
flatten(root->right);
flatten(root->left);
root->right = last;
root->left = nullptr;
last = root;
}
private:
TreeNode* last = nullptr;
};
解法三:
//时间复杂度O(?), 空间复杂度O(n)
/**
* 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:
void flatten(TreeNode* root) {
if(!root) return;
flatten(root->left);
flatten(root->right);
TreeNode* temp = root->right;
root->right = root->left;
root->left = nullptr;
while(root->right) root = root->right;
root->right = temp;
}
};
解法一:
先把右子树展开,然后再把左子树展开后加入到右子树之上。解法一和解法二思路类似。
解法三:
递归法,后序遍历。先左或先右都可以。
2019/11/22 11:30