@@ -724,7 +724,30 @@ \subsubsection{代码}
724
724
递归版
725
725
\begin {Code }
726
726
// LeetCode, Flatten Binary Tree to Linked List
727
- // 递归版1
727
+ // 递归版1,时间复杂度O(n),空间复杂度O(logn)
728
+ class Solution {
729
+ public:
730
+ void flatten(TreeNode *root) {
731
+ if (root == nullptr) return; // 终止条件
732
+
733
+ flatten(root->left);
734
+ flatten(root->right);
735
+
736
+ if (nullptr == root->left) return;
737
+
738
+ // 三方合并,将左子树所形成的链表插入到root和root->right之间
739
+ TreeNode *p = root->left;
740
+ while(p->right) p = p->right; //寻找左链表最后一个节点
741
+ p->right = root->right;
742
+ root->right = root->left;
743
+ root->left = nullptr;
744
+ }
745
+ };
746
+ \end {Code }
747
+
748
+ \begin {Code }
749
+ // LeetCode, Flatten Binary Tree to Linked List
750
+ // 递归版2
728
751
// @author 王顺达(http://weibo.com/u/1234984145)
729
752
// 时间复杂度O(n),空间复杂度O(logn)
730
753
class Solution {
@@ -744,36 +767,6 @@ \subsubsection{代码}
744
767
};
745
768
\end {Code }
746
769
747
- \begin {Code }
748
- // LeetCode, Flatten Binary Tree to Linked List
749
- // 递归版2,时间复杂度O(n),空间复杂度O(logn)
750
- class Solution {
751
- public:
752
- void flatten(TreeNode *root) {
753
- if (root == nullptr) return; // 终止条件
754
- //1.flat the left subtree
755
- if (root->left) flatten(root->left);
756
-
757
- //2.flatten the right subtree
758
- if (root->right) flatten(root->right);
759
-
760
- //3.if no left return
761
- if (nullptr == root->left) return;
762
-
763
- //4.insert left sub tree between root and root->right
764
- //4.1.find the last node in left
765
- TreeNode *p = root->left;
766
- while(p->right) p = p->right;
767
- p->right = root->right;
768
- //4.2.connect right sub tree after left sub tree
769
- p->right = root->right;
770
- //4.3.move left sub tree to the root's right sub tree
771
- root->right = root->left;
772
- root->left = nullptr;
773
- }
774
- };
775
- \end {Code }
776
-
777
770
迭代版
778
771
\begin {Code }
779
772
// LeetCode, Flatten Binary Tree to Linked List
0 commit comments