-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path114.二叉树展开为链表.cpp
More file actions
51 lines (46 loc) · 1.03 KB
/
114.二叉树展开为链表.cpp
File metadata and controls
51 lines (46 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
* @lc app=leetcode.cn id=114 lang=cpp
*
* [114] 二叉树展开为链表
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// 有待优化。时间复杂度空间复杂度均较高。
void flatten(TreeNode* root) {
stack<TreeNode*> heap;
TreeNode* move = root;
while (move)
{
if (move->left)
{
heap.push(move->right);
move->right = move->left;
move->left = nullptr;
}
if (move->right)
{
move = move->right;
}
else if(!heap.empty())
{
move->right = heap.top();
heap.pop();
}
else
{
move = move->right;
}
}
}
};
// @lc code=end