/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* prev_node = NULL;
//先序遍历二叉树的每一个结点
//prev_node记录前一个遍历到的结点
void Pre_Order(struct TreeNode * T){
if(T!=NULL){
struct TreeNode* Left = T->left;
struct TreeNode* Right = T->right;
prev_node->left = NULL;
prev_node->right = T;
prev_node = T;
Pre_Order(Left);//遍历左子树
Pre_Order(Right);//遍历右子树
//注:写成Pre_Order(T->Left); Pre_Order(T->Right);会出错
//因为之前prev_node的操作会改变T->Right的值
}
}
void flatten(struct TreeNode* root){
prev_node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
prev_node->val = 1000;
Pre_Order(root);
}
力扣