Skip to content

Commit 63f8a53

Browse files
committed
add prob #I17.12; iterative solution
1 parent 3358eee commit 63f8a53

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

I17_12_BiNode_LCCI.cpp

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
The data structure TreeNode is used for binary tree, but it can also used to represent a single linked list (where left is null, and right is the next node in the list). Implement a method to convert a binary search tree (implemented with TreeNode) into a single linked list. The values should be kept in order and the operation should be performed in place (that is, on the original data structure).
3+
4+
Return the head node of the linked list after converting.
5+
6+
Note: This problem is slightly different from the original one in the book.
7+
8+
 
9+
10+
Example:
11+
12+
Input: [4,2,5,1,3,null,6,0]
13+
Output: [0,null,1,null,2,null,3,null,4,null,5,null,6]
14+
Note:
15+
16+
The number of nodes will not exceed 100000.
17+
18+
来源:力扣(LeetCode)
19+
链接:https://leetcode-cn.com/problems/binode-lcci
20+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
21+
*/
22+
23+
#include <stack>
24+
using namespace std;
25+
26+
struct TreeNode {
27+
int val;
28+
TreeNode *left;
29+
TreeNode *right;
30+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
31+
};
32+
33+
class Solution {
34+
public:
35+
TreeNode* convertBiNode(TreeNode* root) {
36+
TreeNode* res = NULL;
37+
if(NULL==root) return res;
38+
39+
stack<TreeNode*> s_parent;
40+
stack<bool> s_visited;
41+
TreeNode* tail = NULL;
42+
43+
s_parent.push(root);
44+
s_visited.push(false);
45+
while(!s_parent.empty()){
46+
TreeNode* tmp_node = s_parent.top(); s_parent.pop();
47+
bool tmp_visited = s_visited.top(); s_visited.pop();
48+
if(tmp_visited){
49+
if(res==NULL){
50+
res = tmp_node; // head
51+
tail = tmp_node;
52+
}
53+
else{
54+
tail->right = tmp_node;
55+
tail = tmp_node;
56+
}
57+
tail->left = NULL;
58+
}
59+
else{
60+
//right
61+
if(tmp_node->right){
62+
s_parent.push(tmp_node->right);
63+
s_visited.push(false);
64+
}
65+
//self
66+
s_parent.push(tmp_node);
67+
s_visited.push(true);
68+
//left
69+
if(tmp_node->left){
70+
s_parent.push(tmp_node->left);
71+
s_visited.push(false);
72+
}
73+
}
74+
}
75+
76+
return res;
77+
}
78+
};

0 commit comments

Comments
 (0)