国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

99. Recover Binary Search Tree

2019-11-06 08:50:44
字體:
供稿:網(wǎng)友

問題描述 wo 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? Subscribe to see which companies asked this question.

解決思路 使用inorder遍歷的辦法,因為在二叉查詢樹時,inorder遍歷會滿足遍歷到的節(jié)點是有序的,而此時為升序,所以我們只要找到兩個不滿足pre->val < cur->val的節(jié)點就可以了。

代碼

/** * 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: TreeNode* first=NULL; TreeNode* second=NULL; TreeNode* pre = new TreeNode(INT_MIN); void recoverTree(TreeNode* root) { helper(root); int tmp = first->val; first->val = second->val; second->val = tmp; } void helper(TreeNode* root) { if (root == NULL) return; helper(root->left); if (!first && pre->val >= root->val) first = pre; if (first && pre->val >= root->val) {second = root; } pre = root; helper(root->right); }};
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 神池县| 玛纳斯县| 双峰县| 丽江市| 门头沟区| 南涧| 历史| 眉山市| 恩施市| 古丈县| 翼城县| 涿州市| 安泽县| 五河县| 土默特右旗| 八宿县| 娱乐| 靖安县| 高要市| 苗栗市| 平利县| 文水县| 肇州县| 武清区| 曲靖市| 格尔木市| 江北区| 鄢陵县| 庆城县| 镇平县| 新晃| 沈阳市| 宁国市| 彭泽县| 枣阳市| 崇义县| 东兴市| 肃宁县| 舒兰市| 东方市| 祁阳县|