Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
문제 풀이:
- 순서가 root->left->right 순서: preorder임
- 스택을 사용해서 preorder 순회하기
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<TreeNode*> v;
void Preorder(TreeNode* root){
if(root){
v.push_back(root);
Preorder(root->left);
Preorder(root->right);
}
}
void flatten(TreeNode* root) {
if(!root){
return;
}
Preorder(root);
for(int i=0; i<v.size()-1; i++){
v[i]->left = NULL;
v[i]->right = v[i+1];
}
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 79] Word Search (0) | 2020.10.22 |
---|---|
[leetcode 121] Best Time to Buy and Sell Stock (0) | 2020.10.22 |
[leetcode 136] Single Number (0) | 2020.10.21 |
[leetcode 138] Copy List with Random Pointer (0) | 2020.10.21 |
[leetcode 240] Search a 2D Matrix II (0) | 2020.10.20 |
댓글