首页 > 代码库 > Recover Binary Search Tree
Recover Binary Search Tree
题目
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?
方法
利用BST中序遍历是一个有序的序列。中序遍历BST,遇到顺序错误的则标记,找到两个错误,交换其值即可。若只找到一个,则说明第一个标记的后面的结点,是错误的。public void recoverTree(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode node = root; TreeNode first = null; TreeNode second = null; TreeNode last = null; while (node != null || !stack.isEmpty()) { while(node != null) { stack.push(node); node = node.left; } TreeNode curNode = stack.pop(); if (last == null) { last = curNode; } else { if (last.val > curNode.val) { if (first == null) { first = last; second = curNode; } else { second = curNode; break; } } last = curNode; } node = curNode.right; } int temp = first.val; first.val = second.val; second.val = temp; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。