Recover Binary Search Tree

来源:互联网 发布:class转java工具 编辑:程序博客网 时间:2024/06/06 09:20

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?


/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:void recoverTree(TreeNode *root) {TreeNode *p1 = NULL, *p2 = NULL, *pre = NULL;travel(root, pre, p1, p2);if (p1 && p2) {int temp = p1->val;p1->val = p2->val;p2->val = temp;}}void travel(TreeNode *root, TreeNode *&pre, TreeNode *&p1, TreeNode *&p2) {if (root == NULL)return;travel(root->left, pre, p1, p2);if (pre && root->val < pre->val) {if (!p1) {p1 = pre;p2 = root;}else {p2 = root;}}pre = root;travel(root->right, pre, p1, p2);}};


0 0
原创粉丝点击