【树】114. 二叉树展开为链表

题目:

解答:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     void flatten(TreeNode *root)
15     {
16         if (root == NULL)
17         {
18             return;
19         }
20 
21         TreeNode* left = root->left;
22         TreeNode* right = root->right;
23     
24         if (left)
25         {
26             root->right = left;
27             root->left = NULL;
28     
29             TreeNode* rightmost = left;
30             while(rightmost->right)
31             {
32                 rightmost = rightmost->right;
33             }
34             
35             // point the right most to the original right child
36             rightmost->right = right;
37         }
38         flatten(root->right);
39     }
40 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12817767.html
今日推荐