Skip to content

Latest commit

 

History

History
58 lines (46 loc) · 1 KB

114. Flatten Binary Tree to Linked List.md

File metadata and controls

58 lines (46 loc) · 1 KB
class Solution {
public:
    void flatten(TreeNode* root) {
        while (root) {
            if (root->left) {
                TreeNode* pre = root->left;
                while (pre->right) pre = pre->right;
                pre->right = root->right;
                root->right = root->left;
                root->left = nullptr;
            }
            root = root->right;
        }
    }
};
class Solution {
public:
    void flatten(TreeNode* root) {
        if (!root) return;
        flatten(root->left);
        flatten(root->right);
        TreeNode* right = root->right;
        if (root->left) {
            root->right = root->left;
            root->left = nullptr;
            while (root->right) root = root->right;
            root->right = right;
        }
    }
};
// heap
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* cur = dummy
return dummy->next;

// stack
ListNode dummy(0);
dummy.next = &head;
ListNode* cur = &dummy;
return dummy.next;