114. Flatten Binary Tree to Linked List¶
Tags: Medium
Tree
Depth-first Search
Links: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
/**
* 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) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
if (!root) return;
if (root -> left) flatten(root -> left);
if (root -> right) flatten(root -> right);
TreeNode *tmp = root -> right;
root -> right = root -> left;
root -> left = nullptr;
TreeNode *p = root;
while (p -> right) p = p -> right;
p -> right = tmp;
}
};
递归写法,先让根节点的左右子树达成目标,然后就是链表的操作。
/**
* 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) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
TreeNode * cur = root;
while (cur) {
if (cur -> left) {
TreeNode * p = cur -> left;
while (p -> right) p = p -> right;
p -> right = cur -> right;
cur -> right = cur -> left;
cur -> left = nullptr;
}
cur = cur -> right;
}
}
};
从根节点开始出发,先检测其左子结点是否存在,如存在则将根节点和其右子节点断开,将左子结点及其后面所有结构一起连到原右子节点的位置,把原右子节点连到元左子结点最后面的右子节点之后。
例如,对于下面的二叉树,上述算法的变换的过程如下:
1
/ \
2 5
/ \ \
3 4 6
1
\
2
/ \
3 4
\
5
\
6
1
\
2
\
3
\
4
\
5
\
6