[leetcode]Flatten Binary Tree to Linked List

简单题

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* flat(TreeNode* root){
        if(root == nullptr) return nullptr;
        TreeNode *left = nullptr , *right = nullptr;
        if(root -> left){
            left = flat(root -> left);
        }
        if(root -> right){
            right = flat(root -> right);
        }
        root -> left = nullptr;
        if(left != nullptr){
            root -> right = left;
        }
        if(right != nullptr){
            if(left){
                while(left -> right != nullptr){
                    left = left -> right;
                } 
                left -> right = right;
            }else{
                root -> right = right;
            }
        }
        return root;
    }
    void flatten(TreeNode *root) {
      flat(root);
    }
};

 

----update 2014-07-07---

class Solution {
public:
    TreeNode* make(TreeNode* root) {
        if (root == nullptr) return nullptr;
        TreeNode* tRight = root->right;
        TreeNode* ans = root;
        root->right = make(root->left);
        root->left = nullptr;
        while(root->right) {
            root = root->right;
        }
        root->right = make(tRight);
        return ans;
    }
    void flatten(TreeNode *root) {
        make(root);
    }
};

重写了下,代码简洁点,不过记得就是要把left的指针指向null

 

你可能感兴趣的:(LeetCode)