LetCode 114. 二叉树展开为链表

/**
 * 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) {
        if (root == NULL)
            return;
        if (root->left == NULL && root->right == NULL)
            return;
        if (root->left)
            flatten(root->left);
        if (root->right)
            flatten(root->right);
        TreeNode* left = root->left;
        TreeNode* right = root->right;
        if (left != NULL){
            TreeNode* index = left;
            while(index->right != NULL) index = index->right;
            // 记住要将左子树赋值为NULL,不然会循环下去
            root->left = NULL;
            root->right = left;
            index->right = right;
        }else
            root->right = right;
    }
};

static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();

 

你可能感兴趣的:(LetCode)