LeetCode - 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?

Solution:

(using O(n) space)

 1 /**

 2  * Definition for binary tree

 3  * public class TreeNode {

 4  *     int val;

 5  *     TreeNode left;

 6  *     TreeNode right;

 7  *     TreeNode(int x) { val = x; }

 8  * }

 9  */

10 public class Solution {

11     ArrayList<TreeNode> nodes;

12     ArrayList<Integer> values;

13     public void inOrder(TreeNode root){

14         if(root == null) return;

15         

16         inOrder(root.left);

17         

18         values.add(root.val);

19         nodes.add(root);

20         

21         inOrder(root.right);

22     }

23     public void recoverTree(TreeNode root) {

24         // Start typing your Java solution below

25         // DO NOT write main() function

26         nodes = new ArrayList<TreeNode>();

27         values = new ArrayList<Integer>();

28         inOrder(root);

29         Collections.sort(values);

30         int index = 0;

31         for(TreeNode n : nodes){

32             n.val = values.get(index++);

33         }

34         

35     }

36 }

 

你可能感兴趣的:(Binary search)