题目链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/
题目如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
dfs(root);
}
void dfs(TreeNode* root){//先序遍历,将遍历到的每个节点都放在根节点的右子树,同时左子树要置空
if(!root) return;
//预存好当前节点的左右子树,因为之后会发生变化
TreeNode* left=root->left;
TreeNode* right=root->right;
//把遍历到的节点放到链表中
pre->right=root;
pre=root;
root->left=nullptr;//左子树置空
dfs(left);
dfs(right);
}
private:
TreeNode* dummy=new TreeNode();
TreeNode* pre=dummy;
};