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?
Problem: Find the two nodes in disorder in the binary search tree and exchange them back.
The ordinal traversal of a binary tree must be an incremental sequence. For example, in the BST shown above, the ordinal traversal sequence is 1, 3, 5, 9, 11, 15, and 20. Assume that 3 and 11 are misplaced, as shown in figure
Use firstnode traversal and secondnode traversal to represent the two points of dislocation. In the process of sequential traversal, the point after the first point of dislocation must be smaller than it (5 to 11 is smaller, 11 is the point of dislocation); the second point of dislocation must be smaller than the point above it (3 to 9 ). Recursive methods are used to traverse BST sequentially. If the root of the current traversal point is smaller than the prev value of the previous vertex, there are two possibilities. The first is that Prev is the first point of dislocation, if the firstnode variable is empty, the firstnode value is Prev (row 24th in the Code). The second is that root is the second misplaced vertex. At this time, the firstnode variable is empty, assign the secondnode variable to root (22nd rows in code ).
The Code is as follows:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */10 public class Solution {11 private TreeNode firstNode = null;12 private TreeNode secondNode = null;13 private TreeNode prev = null;14 15 private void traverse(TreeNode root){16 if(root == null)17 return;18 19 traverse(root.left);20 21 if(prev != null && root.val < prev.val){22 secondNode = root;23 if(firstNode == null)24 firstNode = prev;25 }26 prev = root;27 traverse(root.right);28 29 }30 31 public void recoverTree(TreeNode root) {32 traverse(root);33 34 int temp = firstNode.val;35 firstNode.val = secondNode.val;36 secondNode.val = temp;37 }38 }