本文主要是介绍Leetcode 099 Recover Binary Search Tree(二叉树),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目连接:Leetcode 099 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 visitTree(TreeNode* root, vector<int>& nums) {if (root == NULL) return;visitTree(root->left, nums);nums.push_back(root->val);visitTree(root->right, nums);}int countTree(TreeNode* root) {if (root == NULL) return 0;return countTree(root->left) + 1 + countTree(root->right);}void coverTree(TreeNode* root, int start, int end, vector<int>& nums) {if (root == NULL) return;int n = countTree(root->left);coverTree(root->left, start, start + n - 1, nums);root->val = nums[start + n];coverTree(root->right, start + n + 1, end ,nums);}void recoverTree(TreeNode* root) {vector<int> nums;visitTree(root, nums);int n = nums.size();sort(nums.begin(), nums.end());coverTree(root, 0, n-1, nums);}
};
这篇关于Leetcode 099 Recover Binary Search Tree(二叉树)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!