算法分析與設計——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);
	}
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章