LeetCode Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
感觉以前写过blog了,先来个递归版本(注意left指针全部要设置成NULL)
/**
* 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 {
private:
TreeNode* last;
public:
void flatten(TreeNode* root) {
last = NULL;
dfs(root);
}
void dfs(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* r = root->right;
TreeNode* l = root->left;
if (last != NULL) {
last->right = root;
}
last = root;
last->left = NULL;
dfs(l);
dfs(r);
}
};
非递归版本discuss里找的。
/**
* 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) {
while (root) {
if (root->left && root->right) {
TreeNode* largest = root->left;
while (largest->right) {
largest = largest->right;
}
largest->right = root->right;
}
if (root->left) {
root->right = root->left;
}
root->left = NULL;
root = root->right;
}
}
};