From 35ed7a8a7dd7eeabca5c70f24772fe65f980cf70 Mon Sep 17 00:00:00 2001 From: "akash.patil" Date: 2025年2月10日 20:35:11 +0530 Subject: [PATCH] Update 114-flatten-binary-tree-to-linked-list.cpp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Optimizations and Improvements O(n) Time Complexity → Each node is visited at most twice. O(1) Space Complexity → We only use a temporary pointer, eliminating extra recursive calls. Avoids Traversing Right Subtree Repeatedly → Instead of finding the rightmost node repeatedly, we do it only once per left subtree. --- ...114-flatten-binary-tree-to-linked-list.cpp | 39 +++++++++++++------ 1 file changed, 28 insertions(+), 11 deletions(-) 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 によって変換されたページ (->オリジナル) /