【题目】
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
【思路】
题目要求以先序遍历的方式将二叉树转换为只有右树枝的一个树,因此以先序遍历的顺序进行遍历,当左右子树都不为空的时候,将右子树添加到左子树的最右边的树叶节点上,再讲左子树放置到右子树的位置。
【c+代码】
/**
* 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 *tail = root->left;
while (tail->right)
tail = tail->right;
tail->right = root->right;
root->right = root->left;
root->left = NULL;
} else if (root->left)
{
root->right = root->left;
root->left = NULL;
}
root = root->right;
}
}
};