diff --git a/121 Leetcode/114-flatten-binary-tree-to-linked-list.cpp b/121 Leetcode/114-flatten-binary-tree-to-linked-list.cpp index 88006722..c1983a4e 100644 --- a/121 Leetcode/114-flatten-binary-tree-to-linked-list.cpp +++ b/121 Leetcode/114-flatten-binary-tree-to-linked-list.cpp @@ -1,18 +1,35 @@ +// class Solution { +// public: +// void flatten(TreeNode* root) { +// if(!root) return; +// while(root) +// { +// TreeNode* temp = root->right; +// root->right = root->left; +// // root->left = NULL; +// TreeNode* node = root; +// while(node->right) +// { +// node = node->right; +// } +// node->right = temp; +// root = root->right; +// } +// } +// }; class Solution { public: void flatten(TreeNode* root) { - if(!root) return; - while(root) - { - TreeNode* temp = root->right; - root->right = root->left; - root->left = NULL; - TreeNode* node = root; - while(node->right) - { - node = node->right; + while (root) { + if (root->left) { + TreeNode* prev = root->left; + while (prev->right) { + prev = prev->right; + } + prev->right = root->right; + root->right = root->left; + root->left = nullptr; } - node->right = temp; root = root->right; } }

AltStyle によって変換されたページ (->オリジナル) /