1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 11 class Solution 12 { 13 public: 14 void flatten(TreeNode* root) 15 { 16 if(!root) return; 17 flatten(root->left); 18 flatten(root->right); 19 //左右子树皆已转换成链表 20 TreeNode* temp = root->right;//备份扁平后的右孩子 21 root->right = root->left;//右孩子为左孩子 22 root->left = NULL;//左孩子为空 23 while(root->right)//直到它没有右孩子 24 { 25 root = root->right; 26 } 27 root->right = temp;//此时的右孩子为备份的 28 } 29 };
原文地址:https://www.cnblogs.com/yuhong1103/p/12613297.html
时间: 2024-10-08 00:50:47