99. Recover Binary Search Tree
2017-05-15 13:51
393 查看
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?
Subscribe to see which companies asked this question.
这道题目要实现二叉搜索树的两个错误节点的恢复(是在O(n)的空间范围内),首先使用中序遍历找到两个错误的节点,使用一个list的空间代价为O(n),然后再将两个节点的val交换即可,不需要交换两个节点。具体代码如下:
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?
Subscribe to see which companies asked this question.
这道题目要实现二叉搜索树的两个错误节点的恢复(是在O(n)的空间范围内),首先使用中序遍历找到两个错误的节点,使用一个list的空间代价为O(n),然后再将两个节点的val交换即可,不需要交换两个节点。具体代码如下:
public void recoverTree(TreeNode root) {//针对二叉搜索树 //两个节点顺序错误,现在要重新交换两个错误节点,但是不改变树的结构 if(root==null) return; ArrayList<TreeNode> list=new ArrayList<>(); In_Order_Tree(root,list); int begin,end; for ( begin = 0; begin < list.size()-1; begin++) { if (list.get(begin).val>list.get(begin+1).val) { break; } } for ( end = list.size()-1; end >=0; end--) { if (list.get(end).val<list.get(end-1).val) { break; } } int temp=list.get(begin).val; list.get(begin).val=list.get(end).val; list.get(end).val=temp; } private static void In_Order_Tree (TreeNode root,ArrayList<TreeNode> list) { if (root!=null) { In_Order_Tree(root.left, list); list.add(root); In_Order_Tree(root.right, list); } }
相关文章推荐
- [leedcode 99] Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 【LeetCode 99】Recover Binary Search Tree
- leetCode 99: Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- LeetCode 99 Recover Binary Search Tree(Python详解及实现)
- 99. Recover Binary Search Tree
- [leetcode 99] Recover Binary Search Tree
- leetcode hard模式专杀之99. Recover Binary Search Tree
- Leetcode 99 Recover Binary Search Tree
- leetcode || 99、Recover Binary Search Tree
- Leetcode 笔记 99 - Recover Binary Search Tree
- leetcode99 Recover Binary Search Tree java 算法
- leecode 解题总结:99. Recover Binary Search Tree
- Hard-题目19:99. Recover Binary Search Tree
- LeetCode(99)Recover Binary Search Tree