题目:Recover Binary Search Tree
难度:hard
问题描述:
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?
解题思路:
很容易想到搜索二叉树的中序遍历是有序数列。如果遍历结果是1、8、4、5、7、3、10,则知道是第二个结点和第6个结点反掉了。 因此我们可以在中序遍历输出的地方进行判断,如果是错误节点,就保留该节点。具体代码如下:
/ * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { TreeNode t1,t2; TreeNode pre=new TreeNode(Integer.MIN_VALUE); public void recoverTree(TreeNode root) { bfs(root); int temp=t1.val; t1.val=t2.val; t2.val=temp; } private void bfs(TreeNode root) { if(root==null){ return; } bfs(root.left); //中序遍历中间处理 if(t1==null&&pre.val>=root.val){ t1=pre; } if(t1!=null&&pre.val>=root.val){ t2=root; } pre=root; //处理结束 bfs(root.right); } }
讯享网

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/84117.html