Elements of a binary search tree (BST) is 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?
Given a sort of binary tree, and then arbitrarily exchanged two nodes, it is required to restore the original two-fork tree with constant space and without changing the structure.
If the space complexity of O (n), then the direct sequence traversal is good, now with a constant number, then only need to record two times, the middle sequence traversal, the need to move the brain.
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution {TreeNode pre; TreeNode first; TreeNode second; Public voidinorder (TreeNode root) {if(Root = =NULL){ return; } inorder (Root.left); if(Pre = =NULL) {Pre=Root; }Else{ if(Pre.val >root.val) { if(First = =NULL) { First=Pre; } Second=Root; } Pre=Root; } inorder (Root.right); } Public voidrecovertree (TreeNode root) {Pre=NULL; First=NULL; Second=NULL; Inorder (root); if(first!=NULL&& second!=NULL){ intTMP =First.val; First.val=Second.val; Second.val=tmp; } }}
Leetcode Recover Binary Search Tree-----java