Leetcode 897. Increasing Order Search Tree

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/84946407

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Increasing Order Search Tree

2. Solution

  • Version 1
/**
 * 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
/**
 * 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);
    }
};

Reference

  1. https://leetcode.com/problems/increasing-order-search-tree/description/

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试