首页 > 代码库 > LeetCode Recover Binary Search Tree
LeetCode Recover Binary Search Tree
class Solution {private: vector<TreeNode*> nodes;public: void recoverTree(TreeNode *root) { nodes.clear(); dfs(root); // 1 5 3 4 2 6 7 // 1 3 2 4 // 3 2 int len = nodes.size(); if (len < 1) return; int pre = nodes[0]->val; int cur = 0; int first = -1; int second= -1; for (int i=1; i<len; i++) { cur = nodes[i]->val; if (cur < pre) { if (first < 0) { first = i-1; } else { second= i; } } pre = cur; } if (second < 0) second = first + 1; int t = nodes[first]->val; nodes[first]->val = nodes[second]->val; nodes[second]->val= t; } void dfs(TreeNode* root) { if (root == NULL) return; dfs(root->left); nodes.push_back(root); dfs(root->right); }};
先来个"A solution using O(n) space is pretty straight forward"的方法。如果递归调用栈不算额外空间的话,把先序遍历改一下即可,如果算的话...怎么办
来一个伪常数空间的:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {private: vector<TreeNode*> nodes; TreeNode* pre; TreeNode* first; TreeNode* second;public: void recoverTree(TreeNode *root) { nodes.clear(); pre = first = second = NULL; dfs(root); // case a. 1 5 3 4 2 6 7 // case b. 1 3 2 4 // case c. 3 2 // case d. 3 // case e. NULL if (second == NULL) return; // case (d,e) int t = first->val; first->val = second->val; second->val= t; } void dfs(TreeNode* root) { if (root == NULL) return; dfs(root->left); visit(root); dfs(root->right); } void visit(TreeNode* node) { if (pre == NULL) { pre = node; return; } if (node->val < pre->val) { if (first == NULL) { first = pre; second= node; // assume swap with node next to pre(case b,c) } else { second= node; // fix above assumption(case a) } } pre = node; }};
LeetCode Recover Binary Search Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。