Leetcode: recover Binary Search Tree
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. cocould you devise a constant space solution?
Address: https://oj.leetcode.com/problems/recover-binary-search-tree/
Algorithm: two nodes in the binary search tree are incorrectly exchanged. It is required to find the two nodes and exchange them back. Constant space is required. First, search for a binary tree by means of ordinal traversal. When a tree is found to be smaller than its predecessors, it indicates that this is the first error point, that is,, next, find the second error point. The second error point should be counted as B in the first node that is greater than the value of A. Next, change node A and Node B. Pay attention to the situation when point B is the last node. Code:
/** * 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) { if(!root) return ; stack<TreeNode *> stk; TreeNode *p = root; while(p){ stk.push(p); p = p->left; } TreeNode *pre = NULL; p = NULL; TreeNode *swapped_node1 = NULL; bool is_swapped = false; bool find_node = false; while(!stk.empty()){ pre = p; p = stk.top(); stk.pop(); if(!find_node && pre && pre->val > p->val){ swapped_node1 = pre; find_node = true; } if(find_node && p->val >= swapped_node1->val){ if(pre){ int temp = swapped_node1->val; swapped_node1->val = pre->val; pre->val = temp; is_swapped = true; break; } } if(p->right){ TreeNode *q = p->right; while(q){ stk.push(q); q = q->left; } } } if(!is_swapped){ int temp = swapped_node1->val; swapped_node1->val = p->val; p->val = temp; } return ; }};
Leetcode: recover Binary Search Tree