LeetCode#99 Recover Binary Search Tree

题目

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

在这里插入图片描述
在这里插入图片描述

Follow up:

A solution using O(n) space is pretty straight forward.
Could you devise a constant space solution?

原题链接:https://leetcode.com/problems/recover-binary-search-tree/

思路

中序遍历二叉排序树可以得到一个递增序列,将序列出现的元素从小到大进行排序,与中序遍历的结果进行对比,并找出不同的两个值,再到二叉树中找出对应的结点进行修改

代码

/**
 * 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:
	 void recoverTree(TreeNode* root) {
		 if (!root) {
			 return;
		 }
		 vector<int> list;
		 inorderTree(root, list);
		 vector<int> standard(list);
		 
		 for (int i = 0; i < standard.size() - 1; ++i) {
			 for (int j = standard.size() - 1; j > i; --j) {
				 if (standard[j] < standard[j - 1]) {
					 int tmp1 = standard[j];
					 standard[j] = standard[j - 1];
					 standard[j - 1] = tmp1;
				 }
			 }
		 }

		 vector<int> diffVal;
		 for (int i = 0; i < list.size(); ++i) {
			 if (list[i] != standard[i]) {
				 diffVal.push_back(list[i]);
			 }
		 }
		 TreeNode* p = NULL;
		 getVal(root, diffVal[0], p);
		 TreeNode* q = NULL;
		 getVal(root, diffVal[1], q);
		 int tmp = p->val;
		 p->val = q->val;
		 q->val = tmp;
	 }

	 void inorderTree(TreeNode* node, vector<int> &list) {
		 if (!node) {
			 return;
		 }
		 if (node->left) {
			 inorderTree(node->left, list);
		 }
		 list.push_back(node->val);
		 if (node->right) {
			 inorderTree(node->right, list);
		 }
	 }

	 void getVal(TreeNode* root, int val, TreeNode* &res) {
		 if (root->val == val) {
			 res = root;
			 return;
		 }
		 if (root->left) {
			 getVal(root->left, val, res);
		 }
		 if (root->right) {
			 getVal(root->right, val, res);
		 }
	 }
 };
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值