题目
Given a binary tree, flatten it to a linked list in-place.
思路
有两种方法,第一种比较笨,把所有的点按照前序遍历存入队列,然后取出来构建一棵树;还有一种,把左子树的最右叶子节点找到,将右子树作为最右叶子节点的右子树,然后将左子树作为右子树。
代码
思路一
/**
* 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 == NULL) {
return ;
}
std::queue<TreeNode*> s;
helper(s, root);
TreeNode *head = root;
s.pop();
while (s.size() > 0) {
head->right = s.front();
head->left = NULL;
head = head->right;
s.pop();
}
}
void helper(std::queue<TreeNode*>& s, TreeNode* root) {
if (root == NULL) {
return;
}
s.push(root);
helper(s, root->left);
helper(s, root->right);
}
};
思路二
class Solution {
public:
void flatten(TreeNode *root) {
TreeNode*now = root;
while (now)
{
if(now->left)
{
//Find current node's prenode that links to current node's right subtree
TreeNode* pre = now->left;
while(pre->right)
{
pre = pre->right;
}
pre->right = now->right;
//Use current node's left subtree to replace its right subtree(original right
//subtree is already linked by current node's prenode
now->right = now->left;
now->left = NULL;
}
now = now->right;
}
}
};