算法分析与设计——LeetCode Problem.99 Recover Binary Search Tree

题目链接


问题描述


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

Recover the tree without changing its structure.

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


解题思路


恢复二叉搜索树很容易想到中序遍历。这里把每个节点以及节点的值通过中序遍历分别保存到vec1和vec2中,然后对存有节点值的vec2进行排序,最后再将vec2中每个值逐个赋给vec1中的相应节点即可

代码如下

class Solution {
public:
	void recoverTree(TreeNode* root) {
		if (root == NULL) return;
		vector<TreeNode*> list;
		vector<int> vec;
		inorder(root, list, vec);
		int leng = vec.size();
		sort(vec.begin(), vec.end());
		for (int i = 0; i < leng; i++) {
			list[i]->val = vec[i];
		}
	}

	void inorder(TreeNode *root, vector<TreeNode*> &list, vector<int> &vec) {
		if (root == NULL) return;
		inorder(root->left, list, vec);
		vec.push_back(root->val);
		list.push_back(root);
		inorder(root->right, list, vec);
	}
};


猜你喜欢

转载自blog.csdn.net/sysu_chan/article/details/78929608