2013.12.31 19:00
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?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}"
.
Solution:
Two elements in the BST were mistakenly swapped, resulting in an invalid BST. Find that two elements and restore the tree.
Note that the inorder traversal of a binary search tree is a sorted array, that's the rule we need to detect the invalid nodes.
Here we've got two cases to handle:
1. the two elements are adajent, which means they're parent and child.
2. they're separate nodes in the tree.
For the first case, there'll be only on invalid occurrence in the inorder traversal, while the second case would have two invalid occurrences.
Like the following:
1. [1, 2, 4, 3, 5]
2. [5, 2, 3, 4, 1]
You can either find out the invalid nodes during the inorder traversal, or do a thorough traversal and find the invalid nodes in the result array you get.
The latter one is easier in coding, while the former is saves you the extra space to hold the inorder traversal result. I chose the first solution.
Time complexity is O(n), space complexity is O(1), where n is the number of nodes in the tree.
Accepted code:
1 // 2CE, 2WA, 1AC 2 /** 3 * Definition for binary tree 4 * struct TreeNode { 5 * int val; 6 * TreeNode *left; 7 * TreeNode *right; 8 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 void recoverTree(TreeNode *root) { 14 // IMPORTANT: Please reset any member data you declared, as 15 // the same Solution instance will be reused for each test case. 16 17 // 1CE here, incomplete sentence 18 if(root == nullptr){ 19 return; 20 } 21 22 v1 = p1 = nullptr; 23 v2 = p2 = nullptr; 24 f1 = false; 25 26 inorder(root); 27 28 if(p1 == nullptr || p2 == nullptr){ 29 return; 30 } 31 32 int tmp; 33 tmp = p1->val; 34 p1->val = p2->val; 35 p2->val = tmp; 36 } 37 private: 38 bool f1; 39 TreeNode *v1, *v2; 40 // 1CE here, comma missing 41 TreeNode *p1, *p2; 42 43 void inorder(TreeNode *root) { 44 if(root == nullptr){ 45 return; 46 } 47 48 inorder(root->left); 49 v1 = v2; 50 v2 = root; 51 if(f1){ 52 if(v1 != nullptr && v2 != nullptr){ 53 if(v1->val > v2->val){ 54 p2 = v2; 55 } 56 } 57 }else{ 58 if(v1 != nullptr && v2 != nullptr){ 59 if(v1->val > v2->val){ 60 p1 = v1; 61 // 1WA here, should set $p2 62 p2 = v2; 63 // 1WA here, this sentence should be inside if(){} 64 f1 = true; 65 } 66 } 67 } 68 inorder(root->right); 69 } 70 };