File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ // 114.✅ Flatten Binary Tree to Linked List
2+
3+ class Solution
4+ {
5+ public:
6+ void flatten (TreeNode *root)
7+ {
8+
9+ if (root == nullptr )
10+ return ;
11+
12+ stack<TreeNode *> st;
13+ st.push (root);
14+
15+ while (!st.empty ())
16+ {
17+ TreeNode *curr = st.top ();
18+ st.pop ();
19+ if (curr->right )
20+ st.push (curr->right );
21+ if (curr->left )
22+ st.push (curr->left );
23+ if (!st.empty ())
24+ curr->right = st.top ();
25+ curr->left = nullptr ;
26+ }
27+ }
28+ };
29+
30+ // Another Approach
31+
32+ class Solution
33+ {
34+ public:
35+ TreeNode *prev = nullptr ;
36+ void flatten (TreeNode *root)
37+ {
38+ if (root == nullptr )
39+ return ;
40+ flatten (root->right );
41+ flatten (root->left );
42+ root->right = prev;
43+ root->left = nullptr ;
44+ prev = root;
45+ }
46+ };
You can’t perform that action at this time.
0 commit comments