Recover Binary Search Tree leetcode java


題目

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     } 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM