C++Leetcode897:递增顺序查找树

题目
给定一个树,按中序遍历重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
示例 :
在这里插入图片描述
提示:
给定树中的结点数介于 1 和 100 之间。
每个结点都有一个从 0 到 1000 范围内的唯一整数值。

思路
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) {
        vector<int> value;
        TreeNode* newNode=new TreeNode(1);
        TreeNode* p=newNode;
        increasingBST(root,value);
        
        for(int i=0;i<value.size();i++){
            newNode->val=value[i];
            newNode->left=0;
            if(i!=value.size()-1){
                TreeNode* q=new TreeNode(1);
                newNode->right=q;
                newNode=q;
            }
        }
        return p;
    }
    
    void increasingBST(TreeNode* root,vector<int> &value){
        if(root){
            increasingBST(root->left,value);
            value.push_back(root->val);
            increasingBST(root->right,value);  
        }
    }
};

二、简化写法

/**
 * 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) {
        vector<int> value;
        increasingBST(root,value);
        TreeNode* newRoot=new TreeNode(value[0]);
        TreeNode* p=newRoot;
        
        for(int i=1;i<value.size();i++){
            p->left=0;
            p->right=new TreeNode(value[i]);
            p=p->right;
            }
        return newRoot;
        }  
    
    void increasingBST(TreeNode* root,vector<int> &value){
        if(root){
            increasingBST(root->left,value);
            value.push_back(root->val);
            increasingBST(root->right,value);  
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值