본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 114] Flatten Binary Tree to Linked List

by m2162003 2020. 10. 21.

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];
        }
        
    }
};

댓글