Recover Binary Search Tree leetcode java

愛做飯的小瑩子發表於2014-08-05

題目

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?

 

題解

 解決方法是利用中序遍歷找順序不對的兩個點,最後swap一下就好。

 因為這中間的錯誤是兩個點進行了交換,所以就是大的跑前面來了,小的跑後面去了。

 所以在中序便利時,遇見的第一個順序為抵減的兩個node,大的那個肯定就是要被recovery的其中之一,要記錄。

 另外一個,要遍歷完整棵樹,記錄最後一個逆序的node。

 簡單而言,第一個逆序點要記錄,最後一個逆序點要記錄,最後swap一下。

 因為Inorder用了遞迴來解決,所以為了能儲存這兩個逆序點,這裡用了全域性變數,用其他引用型遍歷解決也可以。

 

程式碼如下:

 

 1 public class Solution {
 2     TreeNode pre;
 3     TreeNode first;
 4     TreeNode second;
 5       
 6     public void inorder(TreeNode root){  
 7         if(root == null)  
 8             return;  
 9 
10         inorder(root.left);  
11         if(pre == null){  
12             pre = root;  //pre指標初始
13         }else{  
14             if(pre.val > root.val){  
15                 if(first == null){  
16                     first = pre;//第一個逆序點
17                 }  
18                 second = root;  //不斷尋找最後一個逆序點
19             }  
20             pre = root;  //pre指標每次後移一位
21         }  
22         inorder(root.right);  
23     }  
24       
25     public void recoverTree(TreeNode root) {  
26         pre = null;  
27         first = null;  
28         second = null;  
29         inorder(root);  
30         if(first!=null && second!=null){   
31             int tmp = first.val;  
32             first.val = second.val;  
33             second.val = tmp;  
34         }  
35     } 

相關文章