114. 二叉树展开为链表

 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 };

 

posted @ 2020-04-01 16:08  Jinxiaobo0509  阅读(112)  评论(0)    收藏  举报