99. Recover Binary Search Tree

来源:互联网 发布:telnet开启端口命令 编辑:程序博客网 时间:2024/05/29 15:51

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?





直接思考的是O(n) space的解法,先中序遍历,再排序(虽然只有2个数错位,但是Collections.sort()简单),在回复二叉树

import java.util.ArrayList;import java.util.List;public class Solution {List<Integer> l = new ArrayList<Integer>();int cnt = 0;public void recoverTree(TreeNode root) {    inOrder(root);        Collections.sort(l);        recoverBST(root);    }    private void recoverBST(TreeNode root) {    if(root == null)return;        recoverBST(root.left);root.val = l.get(cnt++);recoverBST(root.right);}private void inOrder(TreeNode root) {if(root == null)return;inOrder(root.left);l.add(root.val);inOrder(root.right);}}


0 0