Recover Binary Search Tree,恢复二叉排序树
问题描述:题意就是二叉树中有两个节点交换了,恢复结构。
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
算法分析:其实还是利用中序遍历,每次记录前一个访问的节点,和当前节点就行比较,如果逆序则记录下来。两个节点交换有两种情况,一种是相邻节点交换,那么只有一个逆序,非相邻节点交换,则有两个逆序。
public class RecoverBinarySearchTree { TreeNode mistake1 = null; TreeNode mistake2 = null; TreeNode pre = null; public void recoverTree(TreeNode root) { inorderTraverse(root); int temp = mistake1.val; mistake1.val = mistake2.val; mistake2.val = temp; } public void inorderTraverse(TreeNode root) { if(root == null) { return; } inorderTraverse(root.left); if(pre != null) { if(pre.val >= root.val)//将当前要访问的根节点和pre比较 { if(mistake1 == null) { mistake1 = pre; } mistake2 = root; } } pre = root;//访问完根节点时,将根节点置为pre,相当于pre指针后移一位 inorderTraverse(root.right); } }