LeetCode 99. Recover Binary Search Tree

原题链接在这里:https://leetcode.com/problems/recover-binary-search-tree/description/

题目:

T

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?

题解:
采用inorder遍历BST应该是返回从小到大的顺序,但这里有两个点顺序错了,所以不会完全从小到大。

如果两个相邻点顺序错了,inorder就应该有一个地方大小顺序颠倒,如果不是相邻点顺序错了,inorder应有两个地方大小顺序颠倒。

e.g. 1234567, 若果2和5调换,结果是1534267, 第一个大小顺序颠倒的“53”中的fist number和第二个大小顺序颠倒的“42”中的second number 调换回来即可。

Time Complexity: O(n). Space: O(logn). stack space.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 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     TreeNode first;
12     TreeNode second;
13     TreeNode prev;
14     public void recoverTree(TreeNode root) {
15         inorderTraverse(root);
16         int temp = first.val;
17         first.val = second.val;
18         second.val = temp;
19     }
20     private void inorderTraverse(TreeNode root){
21         if(root == null){
22             return;
23         }
24         inorderTraverse(root.left);
25         //找到第一次逆序的第一个点
26         if(prev != null && first == null && prev.val >= root.val){
27             first = prev;
28         }
29         //找到最后一次逆序的第二个点, 可能有一次逆序,可能有两次.
30         if(prev != null && first != null && prev.val >= root.val){
31             second = root;
32         }
33         prev = root;
34         inorderTraverse(root.right);
35     }
36 }

 

posted @ 2015-09-10 07:04  Dylan_Java_NYC  阅读(216)  评论(0编辑  收藏  举报