Increasing Order Search Tree

2019-05-25 22:39:56 浏览数 (1)

1. Description

2. Solution

  • Version 1
代码语言:javascript复制
/**
 * 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:
    TreeNode* increasingBST(TreeNode* root) {
        if(!root) {
            return root;
        }
        vector<TreeNode*> nodes;
        inorder(root, nodes);
        for(int i = 0; i < nodes.size() - 1; i  ) {
            nodes[i]->right = nodes[i   1];
        }
        return nodes[0];
    }
    
    void inorder(TreeNode* root, vector<TreeNode*>& nodes) {
        if(!root) {
            return;
        }
        inorder(root->left, nodes);
        root->left = nullptr;
        nodes.push_back(root);
        inorder(root->right, nodes);
    }
};
  • Version 2
代码语言:javascript复制
/**
 * 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:
    TreeNode* increasingBST(TreeNode* root) {
        if(!root) {
            return root;
        }
        TreeNode* head = new TreeNode(0);
        TreeNode* current = head;
        inorder(root, current);
        return head->right;
    }
    
    void inorder(TreeNode* root, TreeNode* current) {
        if(!root) {
            return;
        }
        inorder(root->left);
        root->left = nullptr;
        current->right = root;
        current = root;
        inorder(root->right);
    }
};

0 人点赞