题目:
解答:
先序遍历,将遍历的值插入到尾指针。
注意如何将新根节点的值赋给原根节点。
代码:
class Solution {
public:
TreeNode *newroot = NULL;
TreeNode *last;
void flatten(TreeNode *root) {
if (root == NULL)
return;
newroot = new TreeNode(root->val);
last = newroot;
pre_order(root->left);
pre_order(root->right);
*root = *newroot; //这里需要特殊注意
}
private:
void pre_order(TreeNode * root)
{
if (root == NULL)
return;
TreeNode *next = new TreeNode(root->val);
last->right = next;
last = next;
pre_order(root->left);
pre_order(root->right);
}
};