Recover Binary Search Tree

来源:互联网 发布:mac修改快捷键设置 编辑:程序博客网 时间:2024/04/30 18:03

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. Could you devise a constant space solution?

二叉查找树中序遍历时 一定是增序排列 根据这一性质 进行比较 若不满足增序则记录逆序点 但两次记录的点不同 第一次记录前点第二次记录后点  代码如下:

public class Solution {        TreeNode n1=null;        TreeNode n2=null;        TreeNode pre=null;    public void recoverTree(TreeNode root) {        TreeNode pre=null;        findwr(root);        if(n1!=null&&n2!=null){          int temp = n1.val;          n1.val = n2.val;          n2.val = temp;          }        }    public void findwr(TreeNode root){        if(root==null)return ;        findwr(root.left);        if(pre!=null&&pre.val>root.val){            n2=root;            if(n1==null){                n1=pre;            }        }        pre=root;        findwr(root.right);    }   }


0 0
原创粉丝点击