1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Flatten Binary Tree to Linked List

Posted on 2014-01-01 23:56  1957  阅读(146)  评论(0编辑  收藏  举报

简单题

/**
 * 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