IncredibleThings

导航

LeetCode - Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2
Example 2:

Input: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3
Follow up:

A solution using O(n) space is pretty straight forward.
Could you devise a constant space solution?
binary search tree in order traverse 应该是sorted的
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void recoverTree(TreeNode root) {
        List<TreeNode> nodeList = new ArrayList<>();
        List<Integer> valueList = new ArrayList<>();
        inOrder(root, nodeList, valueList);
        Collections.sort(valueList);
        for (int i = 0; i < valueList.size(); i++) {
            nodeList.get(i).val = valueList.get(i);
        }
    }
    
    public void inOrder(TreeNode root, List<TreeNode> nodeList, List<Integer> valueList) {
        if (root == null) {
            return;
        }
        inOrder(root.left, nodeList, valueList);
        valueList.add(root.val);
        nodeList.add(root);
        inOrder(root.right, nodeList, valueList);
    }
}

 

 

posted on 2020-03-24 09:02  IncredibleThings  阅读(99)  评论(0编辑  收藏  举报