二叉搜索树(BST):它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉搜索树。
形如 4
/ \
2 6
/ \ / \
1 3 5 7
特点是其中序遍历是递增的
利用递归思想中序遍历到第一个子节点:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode pre=new TreeNode(Integer.MIN_VALUE);
TreeNode first=null;
TreeNode second=null;
public void recoverTree(TreeNode root) {
if(root==null)
return;
inorder(root);
int temp=first.val;
first.val=second.val;
second.val=temp;
}
public void inorder(TreeNode root){
if(root!=null){
inorder(root.left);
if(first==null&&pre.val>root.val){
first=pre;
}
if(first!=null&&pre.val>root.val){
second=root;
}
pre=root;
inorder(root.right);
}
}
}