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?
Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
1 /**2 * Definition for binary tree3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One A -TreeNode N1 =NULL; -TreeNode N2 =NULL; theTreeNode pre =NULL; - - Public voidrecovertree (TreeNode root) { - findnodes (root); + if(N1! =NULL&& N2! =NULL) { - inttemp =N1.val; +N1.val =N2.val; AN2.val =temp; at } - } - - voidfindnodes (TreeNode root) { - if(Root = =NULL) { - return; in } - findnodes (root.left); to if(Pre! =NULL&& pre.val >root.val) { + if(N1 = =NULL) { -N1 =Pre; the } *N2 =Root; $ }Panax NotoginsengPre =Root; - findnodes (root.right); the } + A the}
Leetcode Recover Binary Search Tree