栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

记录Leetcoder-恢复搜索二叉树

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

记录Leetcoder-恢复搜索二叉树

题目:
给你二叉搜索树的根节点 root ,该树中的 恰好 两个节点的值被错误地交换。请在不改变其结构的情况下,恢复这棵树 。
示例:

输入:root = [3,1,4,null,null,2]
输出:[2,1,4,null,null,3]
解释:2 不能在 3 的右子树中,因为 2 < 3 。交换 2 和 3 使二叉搜索树有效。

需要使用到的知识点:
1, 中序遍历搜索二叉树得到的元素向量为递增向量。
2,在含有交换位置的递增向量中找到相应的被交换的元素。
3,按照节点val恢复被交换节点的搜索树。
4,最基础最终要的,当然是会中序遍历二叉树啦,哈哈哈哈哈。

code c++ edition:

class Solution {
public:
    void inorder(TreeNode* root, vector & re){
        if (root == nullptr)
            return;
        inorder(root->left, re);
        re.push_back(root->val);
        inorder(root->right, re);
    }

    pair find_swap(vector& res){
        int index1 = -1, index2 = -1;
        int n = res.size();
        for (int i = 0;i< n-1;++i){
            if (res[i+1]val == x || r->val == y) {
				r->val = r->val == x ? y : x;
				if (--count == 0) {
					return;
				}
			}
			recover(r->left, count, x, y);
			recover(r->right, count, x, y);
		}
	}
            
    void recoverTree(TreeNode* root) {
        //中序遍历二叉搜索树,遍历结果返回为vector
        vector inorder_result;
        inorder(root, inorder_result);
        //找到交换顺序的节点,以中序遍历结果向量的索引返回
        pair swap_val = find_swap(inorder_result);
        //将乱序的节点进行交换
        int count =2;
        recover(root, count, swap_val.first, swap_val.second);

    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/738710.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号